Is it possible to kill a spinning thread?

2020-04-11 02:14发布

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

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?

9条回答
Fickle 薄情
2楼-- · 2020-04-11 02:39

As far as Windows goes (from MSDN):

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 certainly doesn't have a thread-killing function.

查看更多
太酷不给撩
3楼-- · 2020-04-11 02:39

As people already said, there is no portable way to kill a thread, and in some cases not possible at all. If you have control over the code (i.e. can modify it) one of the simplest ways is to have a boolean variable that the thread checks in regular intervals, and if set then terminate the thread as soon as possible.

查看更多
我只想做你的唯一
4楼-- · 2020-04-11 02:40

Yes,

Define keepAlive variable as an int . Initially set the value of keepAlive=1 .

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

      }
   }
}

Now, when every you want to kill thread just set the value of keepAlive=0 .

Q. How this works ?

A. Thread will be live until the execution of the function continuous . So it's pretty simple to Terminate a function . set the value of variable to 0 & it breaks which results in killing of thread . [This is the safest way I found till date] .

查看更多
登录 后发表回答