c++ - 暂停 boost::thread 无限时间

标签 c++ multithreading boost boost-thread

我正在使用 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 版本,但我遇到了问题 我得到编译器错误

error: interruptible_wait is not a member of boost::this_thread

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

非常感谢

最佳答案

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

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) 以线程安全的方式更新暂停变量的值。

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

关于c++ - 暂停 boost::thread 无限时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459194/

相关文章:

c++ - 如何在 OpenGL 中捕捉准确的帧率

c++ - 为 ISO 8859-1 实现 basic_string<unsigned char>

c++ - 在 ‘)’ token C++ 之前预期为 ‘&’

c++ - 使用 boost::asio 时的引用问题(我猜)

c++ - 我如何跟踪外部类的 float ?

c++ - 将字符串解析为不区分大小写的 protobuf 枚举

C++ 多线程原子加载/存储

c - 与不同线程共享数据的最快方法?

c++ - 原子读取值的函数?

c++ - boost :将变体与 apply_visitor 进行比较