加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 暂停boost :: thread无限制的时间

发布时间:2020-12-16 05:17:55 所属栏目:百科 来源:网络整理
导读:我使用boost ::线程库(V1.44)来支持C项目中的线程. 用户需要能够暂停在自己的线程中运行的测试循环的执行,无限制的时间 并能随时随地重新开始. 在Windows下,我解决了这个问题 bool ContintueLoop(){if(testLoopPaused){ //testLoopPaused can be set by the
我使用boost ::线程库(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 ::线程无限的时间(直到用户决定恢复它)

非常感谢你

解决方法

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

免责声明:这是从我们在这里的一些类似的代码改编,但我没有尝试编译适应的代码,更不用说验证它实际工作:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读