Intel® Moderncode for Parallel Architectures
Support for developing parallel programming applications on Intel® Architecture.

reading a shared variable

VIKRANT_G_
Beginner
695 Views

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

 

0 Kudos
4 Replies
jimdempseyatthecove
Honored Contributor III
695 Views

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

0 Kudos
VIKRANT_G_
Beginner
695 Views

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

0 Kudos
jimdempseyatthecove
Honored Contributor III
695 Views

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

0 Kudos
Masood_Ali_M_
Beginner
695 Views

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

0 Kudos
Reply