zit*_*eis 10 c++ multithreading boost boost-thread
我正在使用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.
....
}
Run Code Online (Sandbox Code Playgroud)
这没有任何问题,即使知道无限制中断的正确值也会很好.
我开始实现我的程序的linux版本,但我遇到了我得到编译器错误的问题
错误:
interruptible_wait不是成员boost::this_thread
问题:什么是暂停boost :: thread无限时间的好方法(直到用户决定恢复它)
非常感谢你
Ada*_*wen 18
我不知道有任何方法可以使用boost :: thread在任意点暂停一个线程,但是,你所描述的场景可以使用boolean,mutex和condition变量来实现.
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();
}
Run Code Online (Sandbox Code Playgroud)
因此,在您的工作线程中,您可以定期调用block_while_paused()哪个不会返回,直到m_pause设置为false.在主线程中,您调用set_paused(value)以线程安全的方式更新pause变量的值.
免责声明:这是改编自我们在这里的一些类似的代码,但我没有尝试编译改编的代码,更不用说验证它实际工作:)
| 归档时间: |
|
| 查看次数: |
7133 次 |
| 最近记录: |