reading a shared variable

reading a shared variable

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

 

5 帖子 / 0 全新
最新文章
如需更全面地了解编译器优化,请参阅优化注意事项

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

www.quickthreadprogramming.com

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

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

www.quickthreadprogramming.com

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

发表评论

登录添加评论。还不是成员?立即加入