Is it possible to kill a spinning thread?

前端 未结 9 1616
遥遥无期
遥遥无期 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: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 Message;
    
    private:
    
      Active( const Active& );           // no copying
      void operator=( const Active& );    // no copying
    
      bool done;                         // le flag
      message_queue mq;        // le queue
      unique_ptr 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.

提交回复
热议问题