I don’t need to terminate the thread correctly, or make it respond to a “terminate” command. I am interested in terminating the thread forcefully using pure C++11.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could call
std::terminate()from any thread and the thread you’re referring to will forcefully end.You could arrange for
~thread()to be executed on the object of the target thread, without a interveningjoin()nordetach()on that object. This will have the same effect as option 1.You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.
Options 1 and 2 don’t leak intra-process resources, but they terminate every thread.
Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.
There is no portable way in C++11 (that I’m aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.
A
std::threadmay have this member function:You might be able to use this to call an OS-dependent function to do what you want. For example on Apple’s OS’s, this function exists and
native_handle_typeis apthread_t. If you are successful, you are likely to leak resources.