是否可以杀死旋转的线程? [英] Is it possible to kill a spinning thread?

查看:77
本文介绍了是否可以杀死旋转的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ZThreads来说明问题,但我的问题适用于C ++中的PThreads,Boost Threads和其他此类线程库.

I am using ZThreads to illustrate the question but my question applies to PThreads, Boost Threads and other such threading libraries in C++.

class MyClass: public Runnable
{
 public:
  void run()
   {
      while(1)
      {

      }
   }
}

我现在按如下方式启动它:

I now launch this as follows:

MyClass *myClass = new MyClass();
Thread t1(myClass);

现在是否可以杀死(如果需要,可以猛烈地杀死)该线程?我可以肯定地做到这一点,而不是无限循环,我有一个Thread::Sleep(100000),即它正在阻塞.但是我可以杀死一个正在旋转的线程(进行计算).如果是,怎么办?如果没有,为什么不呢?

Is it now possible to kill (violently if necessary) this thread? I can do this for sure instead of the infinite loop I had a Thread::Sleep(100000) that is, if it is blocking. But can I kill a spinning thread (doing computation). If yes, how? If not, why not?

推荐答案

就Windows而言(来自

As far as Windows goes (from MSDN):

TerminateThread是一个危险的函数,仅应在 最极端的情况.仅在以下情况下才应调用TerminateThread 确切知道目标线程在做什么,然后您控制所有 目标线程当时可能正在运行的代码 终止.例如,TerminateThread可能会导致 存在以下问题:

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

Boost当然不具有线程杀死功能.

Boost certainly doesn't have a thread-killing function.

这篇关于是否可以杀死旋转的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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