Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two std::atomic's be part of one union?

Tags:

c++

c++11

atomic

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.

like image 870
alkedr Avatar asked Aug 16 '13 17:08

alkedr


People also ask

Can we use string in Union?

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.

Is STD atomic copyable?

std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.

Is atomic thread safe C++?

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.

Is unsigned int Atomic?

No, fundamental data types (e.g., int , double ) are not atomic, see std::atomic .


1 Answers

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.

like image 60
David Rodríguez - dribeas Avatar answered Oct 19 '22 05:10

David Rodríguez - dribeas