I have an object Foo which has a global variable, Time currentTime
Foo has two methods which are called from different threads.
update()
{
currentTime = currentTime + timeDelay;
}
restart(Time newTime)
{
currentTime = newTime;
}
I am seeing behavior on a restart, the time changes correctly and other times where currentTime does not seem to reset (or it does reset but then update sets it back somehow.
The method update is called roughly every second or so while restart only occurs when a user initiates a restart event (presses a button). I think this is threading timing issue, any suggestions or comments on what is happening are welcome.
You certainly have a race condition here. The most straitforward solution is to protect the use of the shared variable currentTime by using a lock. I am using the Boost.Threads mutex class here:
class Foo
{
boost::mutex _access;
update()
{
boost::mutex::scoped_lock lock(_access);
currentTime = currentTime + timeDelay;
}
restart(Time newTime)
{
boost::mutex::scoped_lock lock(_access);
currentTime = newTime;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With