我使用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 ofboost::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)以线程安全的方式更新暂停变量的值.
免责声明:这是从我们在这里的一些类似的代码改编,但我没有尝试编译适应的代码,更不用说验证它实际工作:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。