升压线程问题 [英] 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 ::线程,从而分离线程,所以你没有等待它完成的方式。我建议存储线程对象为
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.
这篇关于升压线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!