read/write to variable between main thread and worker thread

Viewed 59

In a multi-threaded C++ desktop application, if the main thread has a main loop where:

  • It reads/write to a variable and then
  • Invokes thread that reads/writes to that variable

Does that variable need to be synchronized if the reading/writing between the main thread and the worker thread never happens at the same time? That is the main thread reads/writes to the variable, invokes the thread(s), then waits for the threads to complete before reading/writing the variable again.

1 Answers

Note: the answer below assumed the worker thread is created and joined by the main thread (this turned out to be false - see the update below).


If you are sure that the main thread is accessing the shared data before the worker thread is launched, and will access it later only when the worker thread is joined,
then you don't need to synchronize.

This is because creating a new thread (and joining it) is guarenteed to create a synchronization barrier.
It means that the changes done by the main thread will be visible to the new thread. And when the new thread is done and was joined, the changes it did will be visible to the main thread.

You can see more info in the answer to this question: Does spawning a thread provide memory order guarantees on its own?.


Update:
As you can see in the OP's comment below, a new threads is not actually created. A library using a thread pool is used instead. In this case the need for synchronization is dependent on the library's implementation.
If you are not sure about it - you'd better use a synchronization mechanism.

Related