Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Threading Question

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.

like image 907
Holograham Avatar asked Feb 28 '26 10:02

Holograham


1 Answers

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;
  }
};
like image 85
1800 INFORMATION Avatar answered Mar 03 '26 06:03

1800 INFORMATION