Is it possible to kill a spinning thread?

前端 未结 9 1486
遥遥无期
遥遥无期 2021-01-20 19:09

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: p         


        
相关标签:
9条回答
  • 2021-01-20 19:27

    It is possible to terminate a thread forcefully, but the call to do it is going to be platform specific. For example, under Windows you could do it with the TerminateThread function.

    Keep in mind that if you use TerminateThread, the thread will not get a chance to release any resources it is using until the program terminates.

    0 讨论(0)
  • 2021-01-20 19:27

    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.

    0 讨论(0)
  • 2021-01-20 19:34

    If you need to kill a thread, consider using a process instead.

    Especially if you tell us that your "thread" is a while (true) loop that may sleep for a long period of time performing operations that are necessarily blocking. To me, that indicate a process-like behavior.

    Processes can be terminated in a various number of ways at almost any time and always in a clean way. They may also offer more reliability in case of a crash.

    Modern operating systems offer an array of interprocess communications facilities: sockets, pipes, shared memory, memory mapped files ... They may even exchange file descriptors.

    Good OSes have copy-on-write mechanism, so processes are cheap to fork.

    Note that if your operations can be made in a non-blocking way, then you should use a poll-like mechanism instead. Boost::asio may help there.

    0 讨论(0)
  • Not sure of the other libraries but in pthread library pthread_kill function is available pthread_kill

    0 讨论(0)
  • 2021-01-20 19:35

    Can't you do add something like below

    do {
    
      //stuff here
    
    } while (!abort)
    

    And check the flag once in a while between computations if they are small and not too long (as in the loop above) or in the middle and abort the computation if it is long?

    0 讨论(0)
  • 2021-01-20 19:35

    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] .

    0 讨论(0)
提交回复
热议问题