【问题标题】:Interrupting boost thread中断增强线程
【发布时间】:2012-03-31 03:14:06
【问题描述】:

我希望能够如下中断线程。

void mainThread(char* cmd)
{   
    if (!strcmp(cmd, "start"))
        boost::thread thrd(sender); //start thread

    if (!strcmp(cmd, "stop"))
        thrd.interrupt();       // doesn't work, because thrd is undefined here

}

thrd.interrupt() 是不可能的,因为当我尝试中断 thrd 对象时它是未定义的。我怎样才能解决这个问题?

【问题讨论】:

    标签: c++ multithreading boost boost-thread


    【解决方案1】:

    使用move assignment operator

    void mainThread(char* cmd)
    {   
        boost::thread thrd;
    
        if (!strcmp(cmd, "start"))
            thrd = boost::thread(sender); //start thread
    
        if (!strcmp(cmd, "stop"))
            thrd.interrupt();
    
    }
    

    【讨论】:

      【解决方案2】:

      Boost 线程是可移动的,因此您可以执行以下操作:

      boost::thread myThread;
      if ( isStart ) {
          myThread = boost::thread(sender);
      else if ( isStop ) {
          myThread.interrupt();
      }
      

      如果你想传递它(例如作为函数的参数), 您可能需要使用指针或引用:

      void
      mainThread( std::string const& command, boost::thread& aThread )
      {
          if ( command == "start" ) {
              aThread = boost::thread( sender );
          } else if ( command == "stop" ) {
              aThread.interrupt();
          }
      }
      

      (这可能需要更多。例如,如所写,如果您执行 mainThread( "start" ) 连续两次,你将分离第一个线程, 并且永远无法再次引用它。)

      另一种选择是使用 boost::shared_ptr。

      【讨论】:

      • 在第一个代码的else if 中不应该是isStop 或类似的东西或isStart?。
      • @AdriC.S.是的。我会解决的。
      【解决方案3】:

      这不是关于 boost::thread 的问题,而是关于范围的问题:

      这个:

      if(Condition)
          MyType foo;
      ... // foo is out of scope
      foo.method(); // won't work, no foo in scope
      

      和这个是一样的:

      if(Condition) 
      {
          MyType foo;
      } // after this brace, foo no longer exists, so...
      foo.method(); // won't work, no foo in scope
      

      请注意,上面所有的答案都是这样的:

      MyType foo:
      if (Condition)
          foo.method(); // works because now there is a foo in scope
      else
      {
          foo.otherMethod(); // foo in scope here, too.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-22
        • 2012-05-27
        • 2014-06-26
        • 2012-03-20
        • 2012-11-28
        • 2022-08-03
        相关资源
        最近更新 更多