c++ - 杀死正在运行的线程

标签 c++ windows multithreading

如果我们强制终止正在运行的线程会发生什么

我有一个名为 RecordThread() 的线程,它调用一些复杂且耗时的函数。在这些函数中,我使用了 try-catch block 、分配和释放内存以及使用临界区变量等。

喜欢

  void RecordThread()
  {
    AddRecord();
    FindRecord();
    DeleteRecord();
    // ...
    ExitThread(0);
   } 

创建此线程后,我会在线程完成执行之前立即将其杀死。在这种情况下,如果线程被强行杀死会发生什么?在我们终止线程后,内部函数(AddRecordDeleteRecord)是否完成了它们的执行?

最佳答案

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/

相关文章:

c++ - OpenCV C++ 对 cv::Moments 的使用

c++ - 错误 C2280 : attempting to reference a deleted function (atomic<int>)

windows - 驱动程序安装过程中 Windows 安全对话框中的信息从何而来?

c++ - vector 大小自动失败

python - 如何使用 windows python ping 服务器/网站?

java - 在 Windows 中更改 Java 安全文件

c++ - 使用线程时出现意外输出

java - Android中主线程和AsyncTask之间的ConcurrentLinkedQueue使用

c++ - Long Atomic Int 的实现

c++ - 我应该让每个函数都是静态的,不接触成员变量吗?