- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
hello everyone
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
- Tags:
- Parallel Computing
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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)
Jim Dempsey
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
thanks
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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).
Jim Dempsey
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
-Ali
![](/skins/images/C4F7392A5C68ACA60290C9576F107044/responsive_peak/images/icon_anonymous_message.png)
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page