Ane*_*nan 5 c++ windows multithreading
如果我们强行杀死正在运行的线程会发生什么
我有一个线程RecordThread(),它调用一些复杂和耗时的函数.在这些函数中,我使用try-catch块,分配和释放内存以及使用临界区变量等.
喜欢
void RecordThread()
{
AddRecord();
FindRecord();
DeleteRecord();
// ...
ExitThread(0);
}
Run Code Online (Sandbox Code Playgroud)
创建此线程后,我会在线程完成执行之前立即将其删除.在这种情况下,如果强行杀死线程会发生什么?我们杀死线程后AddRecord,内部函数(,DeleteRecord)是否完成执行?
And*_*ron 13
创建此线程后,我会在线程完成执行之前立即将其删除.
我假设你的意思是你正在TerminateThread()以下列方式使用:
HANDLE thread = CreateThread(...);
// ...
// short pause or other action?
// ...
TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);
Run Code Online (Sandbox Code Playgroud)
如果是这种情况,那么不,执行的线程RecordThread()将在另一个线程调用时准确停止TerminateThread().根据TerminateThread()文档中的注释,这个确切点有点随机,取决于您无法控制的复杂时序问题.这意味着您无法在线程内部进行正确的清理,因此,您应该很少(如果有的话)杀死一个线程.
请求线程完成的正确方法是使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49601 次 |
| 最近记录: |