C ++ Threading Question

I have a Foo object that has a global variable, Time currentTime

Foo has two methods that are called from different threads.

update()
{
    currentTime = currentTime + timeDelay;
}

restart(Time newTime)
{
    currentTime = newTime;
}

I see a reboot behavior, the time changes correctly at other times when currentTime does not look like reset (or it does reset, and then updates it somehow).

A method update is called about every second or so, while a restart only occurs when the user triggers a restart event (presses the button). I think this is a timetable issue, any suggestions or comments on what is happening are welcome.

+3
source share
7 answers

, , . currentTime . mutex Boost.Threads:

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;
  }
};
+9

Thread 1 , currentTime . Thread 2 , currentTime newTime. 2 . 1 , currentTime ( currentTime ) + timeDelay. 1 .

, . , . , , .

, .

+1

printfs , , .

, , update() "currentTime = newTime?"? - - .

, , : http://en.wikipedia.org/wiki/Mutual_exclusion

0

( ) . , , , ..

update()
{
    // Lock mutex
    currentTime = currentTime + timeDelay;
    // unlock mutex
}
// Same idea for restart()

, syncronization, , . , update() currentTime, , , , restart() . update(), ( ) currentTime, (). Mutex , , . Google - , .

/ , /, . - pthreads * nix, Win32. ( pthreads Win32). Boost .

0
. InterlockedExchange InterlockedAdd.
0

, , . , - , . - , , , . , , . , , .

, , current_time. - , .

0

currentTime , , , . (PTHREAD_MUTEX_INITIALIZER BOOST.call_once)

BOOST.Threads , Foo, , mutex _access ( prefex!) currentTime.

currentTime , BOOST.Threads .

0

Source: https://habr.com/ru/post/1708866/


All Articles