【问题标题】:Pausing a boost::thread for unlimited time无限时间暂停 boost::thread
【发布时间】:2011-05-26 10:38:17
【问题描述】:

我正在使用 boost::thread 库 (V1.44) 来支持我的 C++ 项目中的线程。

用户需要能够无限期暂停在自己的线程中运行的测试循环的执行 并且可以随时恢复。

在Windows下我是这样解决的

bool ContintueLoop(){
if(testLoopPaused){ //testLoopPaused can be set by the user via  GUI elements
  try{
      boost::this_thread::interruptible_wait( 2147483648 ); //that's very ugly,
      // somebody knows the right way to pause it for a unlimited time?
      return true;
     }
  catch( boost::thread_interrupted& e ){ //when the user selects resume the 
      // the thread is interrupted and continues from here
      testLoopPaused = false;
      return true;
     }
if( ... ) //test for other flags like endTestLoop etc.
  ....
}

这没有任何问题,即使知道无限中断的正确值会很好。

我开始实现我的程序的 linux 版本,但我遇到了问题 我得到编译器错误

错误:interruptible_wait 不是boost::this_thread 的成员

问题:什么是暂停 boost::thread 无限时间的好方法(直到用户决定恢复它)

非常感谢

【问题讨论】:

  • 没有像Suspend()这样的命令吗?
  • @sad_man,不,没有。有一个 sleep 函数可以将线程挂起一段定义的时间,但我不认为挂起的线程可以在随机时间恢复

标签: c++ multithreading boost boost-thread


【解决方案1】:

我不知道有任何方法可以使用 boost::thread 在任意点暂停线程,但是,您描述的情况可以使用布尔值、互斥体和条件变量来实现。

bool m_pause; // initialise to false in constructor!
boost::mutex m_pause_mutex;
boost::condition_variable m_pause_changed;

void block_while_paused()
{
    boost::unique_lock<boost::mutex> lock(m_pause_mutex);
    while(m_pause)
    {
        m_pause_changed.wait(lock);
    }
}

void set_paused(bool new_value)
{
    {
        boost::unique_lock<boost::mutex> lock(m_pause_mutex);
        m_pause = new_value;
    }

    m_pause_changed.notify_all();
}

因此,在您的工作线程中,您可以定期调用block_while_paused(),直到 m_pause 设置为 false 才会返回。在您的主线程中,您调用 set_paused(value) 以线程安全的方式更新 pause 变量的值。

免责声明:这是改编自我们这里的一些类似代码,但我没有尝试编译改编后的代码,更不用说验证它是否真的有效:)

【讨论】:

  • @Adam,这看起来很有希望。我将尝试实施并报告,谢谢!
  • 如果你有某种类代表你的工作线程,最好的办法是将所有这些都放在类中,将除set_paused 之外的所有内容设为私有,这样它就不能被滥用。唯一需要注意的是 mutexcondition_variable 不能被复制,这(取决于你如何使用 boost 创建线程)可能会带来一些不便。
  • 现在只要放入一个队列,就可以完全控制线程了;) @Adam:小话说,你不必解锁到notify_all(),这样可以稍微简化你的代码。
  • 我知道,但我通常会尽量在最短的时间内持有互斥锁 :)。
  • @Adam:反应有点晚,但我在想调用者释放锁然后被抢占的情况。线程想要暂停,所以它需要锁检查条件并被抢占。然后调用者在线程等待之前通知,所以线程错过了通知,不会做出反应。你可能认为这永远不会发生,但在负载情况下某些线程没有反应时可能值得检查......
【解决方案2】:

如果有人仍然需要提到的功能(在事件发生之前休眠线程)并且习惯使用 boost 库,那么 Boost.Interprocess 库提供 Semaphore 机制,可以用作有问题的描述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多