Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility in concurrent C++ programs

I know in Java visibility of a member is not guaranteed when accessing it from another thread.

The meaning is the accessing thread will maybe see a stole value of the member (becuase the cache has not been flushed to main memory yet).

I wonder if that is the case for C++ too? (also in C++11?)

If so, how do you solve this problem in C++? (In Java, you can use the synchronized keyword).

like image 452
user1028741 Avatar asked Dec 31 '25 02:12

user1028741


2 Answers

You can use std::atomic<T> as type of the member. This guarantees a set of atomic operations, like fetch and increment. This is general much better than adding a mutex, as these operations are implemented with special atomic instructions of the CPU

like image 191
ragazzojp Avatar answered Jan 02 '26 14:01

ragazzojp


Visibility of threads is a general problem with threads and not with language. In C++ visibility problems are due to bad logic, which is a code that may run without any issues without implementing a Mutex to the resource or value being accessed, if the logic is valid then the code will compile and run without any problems but the values expected may not be what you wanted.

To solve it you used a Mutex object and lock the variable being accessed. But C++11 tackles this problem even further with std::atomic. The atomic variable is a flag that encapsulates the Mutex behavior and frees you from calling lock and unlock.

like image 39
Claudiordgz Avatar answered Jan 02 '26 16:01

Claudiordgz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!