I have the following code:
MyClass::aMethod()
{
...
bool isStarted = false;
boost::thread(boost::bind(&MyClass::CheckTimeoutThread, this, isStarted));
...//some time later
isStarted = true;
...
}
MyClass::checkTimeoutThread(bool &isStarted)
{
...//some code here
while(anotherFlag)
{
...//do something
if(isStarted)//ALWAYS THE INITIAL VALUE OF FALSE
{
}
...
}
}
I was expected the isStarted variable can be used as a flag but I am wrong or I was doing something wrong.
The
boost::thread
will store copy of its arguments. But you can simulate a reference by passing areference_wrapper
with the help ofboost::ref
. Also note that you don't need to callboost::bind
:But note that you now have a race condiiton on
isStarted
. You need to either synchrise access to it with, say, mutexes, or use an atomic type, if available on your platform (if you have C++11, then you can usestd::atomic<bool>
, as suggested by @PeteBecker.)Edit Obviously all of the above assumes that
isStated
lives at least as long as thethread
that uses it. In practice, this means the thread must be done by the timeaMethod
returns. Alternatively, you can makeisStarted
a data member. But you still have to make sure to join the thread before theMyClass
destructor destroys it.