如果我们强制终止正在运行的线程会发生什么
我有一个名为 RecordThread()
的线程,它调用一些复杂且耗时的函数。在这些函数中,我使用了 try-catch block 、分配和释放内存以及使用临界区变量等。
喜欢
void RecordThread()
{
AddRecord();
FindRecord();
DeleteRecord();
// ...
ExitThread(0);
}
创建此线程后,我会在线程完成执行之前立即将其杀死。在这种情况下,如果线程被强行杀死会发生什么?在我们终止线程后,内部函数(AddRecord
、DeleteRecord
)是否完成了它们的执行?
最佳答案
After creating this thread, I am immediately killing it before the thread completes its execution.
我假设您的意思是您正在以下列方式使用 TerminateThread()
:
HANDLE thread = CreateThread(...);
// ...
// short pause or other action?
// ...
TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);
如果是这种情况,则不会,执行 RecordThread()
的线程将在另一个线程调用 TerminateThread()
时的确切位置停止.根据 TerminateThread()
中的注释文档,这个确切的点有点随机,取决于复杂的时间问题,这是你无法控制的。这意味着您无法在线程内处理适当的清理,因此,you should rarely, if ever, kill a thread .
请求线程完成的正确方法是使用 WaitForSingleObject()
,如下所示:
HANDLE thread = CreateThread(...);
// ...
// some other action?
// ...
// you can pass a short timeout instead and kill the thread if it hasn't
// completed when the timeout expires.
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
关于c++ - 杀死正在运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10737417/