I am trying to do the followings
class a{
public:
void Start();
void Tick();
boo开发者_如何学运维l 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));
}
}
My environment is vs2005 and win7.
However, I always got the access violation in the debug.
An access violation in this case would indicate that the thread is running beyond the lifetime of the a
object.
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.
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.
IsTimeOut
should be volatile
if accessed from multiple threads, i.e.
volatile bool IsTimeOut;
Take a look at this DDJ article.
If you show more of your code and also explain how the IsTimeOut
is changed it might be easier to say what goes wrong. In general, it looks like you have multiple threads and the first creates a
, but what does that thread do then? Will a
go out of scope and thus be destroyed? If so, then the timer thread will for sure have an access violation as the object is no longer available.
精彩评论