无限时间暂停boost::线程 我使用Booo::线程库(V1.44)来支持C++项目中的线程。

无限时间暂停boost::线程 我使用Booo::线程库(V1.44)来支持C++项目中的线程。,c++,multithreading,boost,boost-thread,C++,Multithreading,Boost,Boost Thread,用户需要能够无限时间地暂停在自己线程中运行的测试循环的执行 只要他愿意,随时可以恢复 在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,

用户需要能够无限时间地暂停在自己线程中运行的测试循环的执行 只要他愿意,随时可以恢复

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

错误:
interruptable\u wait
不是
boost::this\u线程的成员

问题:暂停boost::线程无限期的好方法是什么(直到用户决定继续)


非常感谢

我不知道使用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();
}
bool m_pause;//在构造函数中初始化为false!
mutex m_pause_mutex;
boost::条件变量m\u pause\u已更改;
暂停时无效块\u()
{
boost::唯一的锁定(m_pause\u mutex);
while(m_暂停)
{
m_pause_已更改。等待(锁定);
}
}
已暂停无效集(布尔新值)
{
{
boost::唯一的锁定(m_pause\u mutex);
m_pause=新的_值;
}
m_pause_已更改。通知_all();
}
因此,在工作线程中,您可以在暂停时定期调用
block\u()
,直到m\u pause设置为false后才会返回。在主线程中,可以调用
set\u paused(value)
以线程安全的方式更新pause变量的值


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

如果有人仍然需要提到的功能(在事件发生之前休眠线程)然后使用boost库就很舒服了。进程间库提供了信号量机制,可以像前面提到的那样使用。

没有像
Suspend()
这样的命令吗?@sad\u-man,没有。有一个sleep函数,它将在定义的时间内挂起线程,但我认为挂起的线程不能随机恢复time@Adam,这看起来很有希望。我将尝试实施并报告,谢谢!如果你有一个代表你的工作线程的类,最好的办法就是把所有的东西都放在这个类中,使所有的东西都是私有的,而不是
set\u
private,这样它就不会被滥用。唯一需要注意的是,
mutex
condition\u variable
无法复制,这(取决于您使用boost创建线程的方式)可能会带来一些不便。现在只需放入队列,就可以完全控制线程;)@亚当:小意思,你不必解锁通知_all(),这会简化你的代码。我知道,但我通常会尽量在最短的时间内保持互斥:)。@Adam:反应有点晚,但我在想调用方释放锁然后被抢占的情况。线程想要暂停,因此它需要锁来检查条件并被抢占。然后,调用方在线程等待之前发出通知,因此线程将错过通知而不会做出反应。您可能认为这种情况永远不会发生,但在负载情况下,某些线程没有反应时,检查它可能是值得的。。。