I am relatively new to parallel programming and have the following doubt:-
is reading a shared variable(that is not modified by any thread) without using locks a good practice
thanks for the help in advance
- Parallel Computing
Reading a shared variable by multiple threads is fine. In fact it is almost always preferred over reading copies of the variable by multiple threads. (reduces shared cache requirements)
hi jim, thanks for the info
also how do the threads behave when they access this shared variable, i mean since i do not have locks on the variable each thread is free to access it anytime. what if one thread is accessing it and another thread wants to access it at the same time.
No issues with respect to concurrent reads.
You would have an issue with concurrent writes, even with an X++; which is a single instruction Read/Modify/Write operation. For concurrent update, you have to protect the update using atomic operations (e.g. !$omp atomic), sync_fetch_and_add, or critical section (!$omp critical).
Note, you can also safely have one tread perform the writes while all other threads read. You may have to attribute the variable with volatile or use an atomic type (if your C++ library has atomic typing).
Only reading a variable without any modifications doesn't cause any harm though it may some times lead to ambiguity it doesnot cause any harm.
on the case of locking down of variables it is a good way of protecting your transactions from concurrency conflicts as any number of users may access the variable at the same time if it is not locked down. Modification and write operations on the same variable by many users may lead to non-atomicity and Dead lock conditions
Hope you found it useful.