Is it possible to kill a spinning thread?

前端 未结 9 1487
遥遥无期
遥遥无期 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:43

    You can with TerminateThread() API, but it is not recommended.

    More details at: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx

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

    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.

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

    A general solution to the kind of question posted can be found in Herb Sutter article: Prefer Using Active Objects Instead of Naked Threads

    This permits you to have something like this (excerpt from article):

    class Active {
    public:
      typedef function<void()> Message;
    
    private:
    
      Active( const Active& );           // no copying
      void operator=( const Active& );    // no copying
    
      bool done;                         // le flag
      message_queue<Message> mq;        // le queue
      unique_ptr<thread> thd;          // le thread
    
      void Run() {
        while( !done ) {
          Message msg = mq.receive();
          msg();            // execute message
        } // note: last message sets done to true
      }
    

    In the active object destructor you can have then:

    ~Active() {
        Send( [&]{ done = true; } ); ;
        thd->join();
      }
    

    This solution promotes a clean thread function exist, and avoids all other issues related to an unclean thread termination.

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