我正在使用 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 ofboost::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/