杀死正在运行的线程 [英] Kill a running thread

查看:91
本文介绍了杀死正在运行的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们强行杀死正在运行的线程会发生什么情况

What happens if we forcefully kill a running thread

我有一个名为RecordThread()的线程,该线程调用了一些复杂且耗时的函数.在这些函数中,我使用 try-catch 块,分配和释放内存以及使用关键节变量等.

I have a thread namely RecordThread() which calls some complex and time consuming functions. In these functions I am using try-catch blocks, allocating and deallocation memory and using critical section variables etc.

喜欢

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

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

After creating this thread, I am immediately killing it before the thread completes its execution. In this case what happens if the thread is forcefully killed? Do the internal functions (AddRecord, DeleteRecord) complete their execution after we killed the thread?

推荐答案

创建此线程后,我将在该线程完成其执行之前立即将其杀死.

After creating this thread, I am immediately killing it before the thread completes its execution.

我假设您是说您正在以以下方式使用TerminateThread():

I assume you mean you are using TerminateThread() in the following fashion:

HANDLE thread = CreateThread(...);

// ...
// short pause or other action?
// ...

TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);

如果是这种情况,那么否,执行RecordThread()的线程将完全停止,而另一个线程调用TerminateThread()时该线程将停止在该位置.根据 TerminateThread() 文档中,这一确切点在某种程度上是随机的,并且取决于您无法控制的复杂时序问题.这意味着您无法在线程内部进行适当的清理,因此,您很少(如果有的话)杀死线程

If that is the case, then no, the thread executing RecordThread() will be stopped exactly where it is at the time that the other thread calls TerminateThread(). As per the notes in the TerminateThread() documentation, this exact point is somewhat random and depends on complex timing issues which are out of your control. This implies that you can't handle proper cleanup inside a thread and thus, you should rarely, if ever, kill a thread.

请求完成线程的正确方法是使用WaitForSingleObject(),如下所示:

The proper way to request the thread to finish is by using WaitForSingleObject() like so:

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);

这篇关于杀死正在运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆