How can I use std :: atomic_compare_exchange_ *, etc. With arbitrary pointers?

InterlockedCompareExchange on Windows, as well as __sync_val_compare_and_swap in gcc accept pointers, and so I can pass any address, for example. pointing to a shared memory block for these functions.

For non-x86 architectures, I may need to ensure correct memory alignment, and for x86 (and possibly others), perhaps I want to ensure line alignment for performance, although correctness should not be a problem (-> x86 LOCK ).

Trying to get rid of some platform-dependent things in my code (Windows VC ++ vs GCC), I looked at C ++ 11 atomic_compare_exchange_weak and friends. But they all work with a variable like std::atomic<T>* .

Is there a way to use arbitrary pointers with C ++ 11 atomic functions? This is not like a simple cast to std :: atomic that will help solve this problem.

+4
source share
1 answer

Short answer: they cannot. This is necessary for language portability, because C ++ does not want to require support from each platform without blocking for a specific set of data sizes. Using std::atomic<T> allows the library to transparently provide atomicity locks for some T and use locks for others.

On the bright side, replacing T with atomic<T> in your code base provides documentation about which objects are used for synchronization and provides protection against accidental non-atomic access to these objects.

Long answer: reinterpret_cast<std::atomic<decltype(t)>&>(t).store(value) may actually work on some implementations during the correct phase of the moon, but this is the purest evil.

+2
source

Source: https://habr.com/ru/post/1485551/


All Articles