parts/6.60.Concurrency-DirectedTermination-CGT.md

6.60 Concurrency – Directed termination [CGT]

6.60.1 Applicability to language

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
    t.request_stop(); // no-op
    t2.request_stop(); // stop_token tok signalled
} 

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.

6.60.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can: