10

我正在使用 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 无限时间的好方法(直到用户决定恢复它)

非常感谢你

4

2 回答 2

18

我不知道有任何方法可以使用 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)以线程安全的方式更新暂停变量的值。

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

于 2010-12-16T09:43:57.840 回答
1

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

于 2014-01-30T11:10:30.203 回答