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 intervening join()
nor detach()
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::thread
may have this member function:
native_handle_type native_handle();
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_type
is a pthread_t
. If you are successful, you are likely to leak resources.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…