If there are two threads that just read a global variable, is it necessary to use mutex to lock and unlock the global variable?
But to answer your question, any thread can access any global variable currently in scope.
When a new thread is spawned, 4Test creates a new copy of all local variables and function arguments for it to use. However, all threads have equal access to global variables. To avoid a situation in which multiple threads modify a variable simultaneously, you must declare the variable as shareable.
You should use volatile keyword to keep the variable updated among all threads. Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.
Only one thread can read and write a shared variable at a time. When one thread is accessing a shared variable, other threads should wait until the first thread is done.
If the threads are only reading the variable and nobody is writing to it (not one of the threads, not someone else), then you're perfectly fine without locks. If any concurrent modification could happen, then everyone (including pure readers) must be synchronised somehow - by a mutex, a read/write lock or in some other way.
In general, exclusive access is required to prevent one from seeing an inconsistent state. For a reader thread, this means avoiding partial reads.
What does that mean ? Imagine that you have a value stored on two (atomic) integers, for example coordinates.
int i = 3;
int j = 4;
Now, we are going to read i
and j
whilst they undergo modification, more precisely when a Writer
thread want to move in a diagonal fashion from (3, 4)
to (4, 5)
:
Reader Writer
| |
| i = 4
| |
i = 4 <pause>
j = 4 |
| j = 5
| |
This is called a partial read: the Reader
thread has gotten information that the object is at (4, 4)
even though it was never there. I'll let you think what occurs if those coordinates are used to compute the trajectory of a plane...
Avoiding partial reads however is fairly easy: mutations should be seen atomically.
And thus, to answer your question, if the only accesses are read accesses, the no synchronization is required. But if you sometimes (even infrequently) modify the information read, then you need some mechanism.
If they're just reading, then you don't need locking.
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