Visibility in concurrent C++ programs

953 Views Asked by At

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).

3

There are 3 best solutions below

5
On

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

2
On

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.

0
On

C++ (not 11) doesn't support concurrency natively, it's provided by extensions. The two I primarily use are OpenMP and pthreads. The visibility and atomicity of things are based on what extension you're using.

  • OpenMP uses #pragma omp barrier to synchronise threads. It also has 'directives' such as atomic and critical to limit access on things.
  • pthreads synchronises on certain functions, see section 4.11 of this page to see which functions cause synchronisation. Pretty much: if you use a mutex you're fine.
  • For C++11 see the bottom of this page, you may find something useful there but I haven't worked enough with C++11 concurrency to say much.

The key point is, synchronicity is based on the multi-threading extension you're using.

In addition to the above if you're doing scientific work there's OpenMP which has all data transfer between threads explicit and so has no such worries.