問題描述
我不需要正確終止線程,或者讓它響應終止"命令.我有興趣使用純 C++11 強行終止線程.
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.
推薦答案
您可以從任何線程調用
std::terminate()
并且您所指的線程將強制結束.
You could call
std::terminate()
from any thread and the thread you're referring to will forcefully end.
你可以安排 ~thread()
在目標線程的對象上執行,無需介入 join()
或 detach()
在那個對象上.這將具有與選項 1 相同的效果.
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.
選項 1 和 2 不會泄漏進程內資源,但它們會終止每個線程.
Options 1 and 2 don't leak intra-process resources, but they terminate every thread.
選項 3 可能會泄漏資源,但部分合作,因為目標線程必須同意拋出異常.
Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.
在 C++11(我知道)中沒有可移植的方式來非合作地殺死多線程程序中的單個線程(即不殺死所有線程).沒有動力設計這樣的功能.
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.
一個 std::thread
可能有這個成員函數:
A std::thread
may have this member function:
native_handle_type native_handle();
您也許可以使用它來調用依賴于操作系統的函數來執行您想要的操作.例如在 Apple 的操作系統上,這個函數存在并且 native_handle_type
是一個 pthread_t
.如果你成功了,你很可能會泄漏資源.
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.
這篇關于如何在 C++11 中終止線程?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!