This vulnerability as specified in ISO/IEC 24772-1 clause 6.60 is mitigated in C++, as long as the standard library facilities for threads are used. C++ does not provide the means to terminate a thread asynchronously. Instead C++ allows cooperative termination through the use of std::stop_token
, however, a thread instructed by a stop request to cease execution can ignore such a request. For example, using std::jthread::request_stop()
to send a stop request to the started thread, the created thread can have a thread function that never handles such a stop request.
void some_function(int some_arg);
void other_function(std::stop_token tok, int some_arg);
int main(){
std::jthread t(some_function,42); // stop_token ignored
std::jthread t2(other_function,42); // stop_token passed
// no-op
t.request_stop(); // stop_token tok signalled
t2.request_stop(); }
In the above example, at the end of the main function the destructors of the thread objects t and t2 will call this->request_stop()
and this->join()
. If one of the thread functions never returns, then the corresponding join()
call will block.
Other programmed mechanisms can be constructed to cause another thread to complete, such as setting a shared variable to a known value that the target thread reads and then terminates itself.
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Follow the avoidance mechanisms of ISO/IEC 24772-1 clause 6.60.5.
Use static analysis tools and code reviews to ensure that threads accepting stop requests handle the request.