Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it dangerous to read global variables from separate threads at potentially the same time?

So I'm writing this neat little program to teach myself threading, I'm using boost::thread and C++ to do so.

I need the main thread to communicate with the worker thread, and to do so I have been using global variables. It is working as expected, but I can't help but feel a bit uneasy.

What if the the worker thread tries write to a global variable at the same time as the main thread is reading the value. Is this bad, dangerous, or hopefully taken into account behind the scenes??

like image 267
ch0l1n3 Avatar asked Feb 18 '15 18:02

ch0l1n3


Video Answer


2 Answers

§1.10 [intro.multithread] (quoting N4140):

6 Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

23 Two actions are potentially concurrent if

  • they are performed by different threads, or
  • they are unsequenced, and at least one is performed by a signal handler.

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.

Purely concurrent reads do not conflict, and so is safe.

If at least one of the threads write to a memory location, and another reads from that location, then they conflict and are potentially concurrent. The result is a data race, and hence undefined behavior, unless appropriate synchronization is used, either by using atomic operations for all reads and writes, or by using synchronization primitives to establish a happens before relationship between the read and the write.

like image 109
T.C. Avatar answered Dec 26 '22 07:12

T.C.


If your different threads only read values of global variables, there will be no problem.

If more than one thread tries to update same variable (example read, add 1 write), then you must use a synchronization system to ensure that the value cannot be modified between the read and the write.

If only one thread writes while others read, it depends. If the different variables are unrelated, say number of apples and oranges in a basket, you do not need any synchronization, provided you accept not exactly accurate values. But if the values are related say amount of money on two bank accounts with a transfert between them, you need synchronization to ensure that what you read is coherent. It could be too old when you use it because it has already be updated but you have coherent values.

like image 21
Serge Ballesta Avatar answered Dec 26 '22 07:12

Serge Ballesta