I want to do this:
union {
std::atomic<uint128_t> u128;
struct {
std::atomic<uint64_t> u64_1;
std::atomic<uint64_t> u64_2;
};
};
Several threads will read and write both parts of the union.
Is it safe?
Edit: I use Linux, x86_64, clang 3.3
Edit2: I want to be able to increment and decrement u64_1, read u64_2, and write u128 (compare_exchange)
Edit3: What if I use atomic builtin functions? The union will look like this:
union {
uint128_t u128;
struct {
uint64_t u64_1;
uint64_t u64_2;
};
};
u64_1 will map to first half of u128 and u64_2 will map to second half.
Defining a Union Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data.
std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.
In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.
No, fundamental data types (e.g., int , double ) are not atomic, see std::atomic .
The std::atomic<T>
operations can be either lockless or locking, depending on whether the architecture offers the underlying guarantees. You can check this by checking std::atomic<T>::is_lock_free()
.
If the type is not lock free, it might be supported by the library by means of a counter. That in turn probably means that the type is no longer a POD underneath, which in turn means that it is your responsibility to call the constructors/destructors when switching from one active member of the union to another.
If there is a mutex for the 128 bit but not the 64bit types you might end up with a situation in which the layout of the values coincides, but the atomicity of operations is guaranteed by different means, so it might seem to work, but fail spuriously and in a way that is hard to even detect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With