Boost线程问题 [英] Boost thread questions
问题描述
我想尝试以下操作
class a{
public:
void Start();
void Tick();
bool IsTimeOut;
};
void a::Start()
{
boost::thread thread1(boost::bind(&a::Tick,this));
}
void a::Tick()
{
while(!IsTimeOut)
{
boost::this_thread::sleep(boost::posix_time::millisec(1000));
}
}
我的环境是vs2005和win7。
My environment is vs2005 and win7.
但是,我总是在调试中遇到访问冲突。
However, I always got the access violation in the debug.
推荐答案
在这种情况下的违例表示线程运行超过 a
对象的生命周期。
An access violation in this case would indicate that the thread is running beyond the lifetime of the a
object.
IsTimeOut
需要是原子的或者由互斥体保护,如果它是由另一个线程写的,否则您的程序可能无法正常工作,但这不应该导致访问冲突。
IsTimeOut
needs to either be atomic or protected by a mutex if it is written by another thread, otherwise your program might not work correctly, but this shouldn't cause the access violation.
您立即销毁 boost :: thread
对象,因此分离线程,因此您无法等待它完成。我建议将线程对象存储为 a
的成员变量,并在 a
的析构函数中加入它,或提供与线程联接的显式 wait()
成员函数。
You are destroying the boost::thread
object immediately, and thus detaching the thread, so you have no way of waiting for it to finish. I would suggest storing the thread object as a member variable of a
, and either joining with it in the destructor of a
or providing an explicit wait()
member function that joins with the thread.
这篇关于Boost线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!