Std :: atomic_store and std :: atomic_exchange do not exchange

According to en.cppreference.com , std::atomic_exchangeand are std::atomic_storethread safe std::swap. But this is not the behavior that I get with g ++ or clang ++.

Real time problem on coliru. (see below)

He prints this though:

std::atomic_store

a: 0x1ed2c30    0
b: 0x1ed2c50    1

a: 0x1ed2c50    1
b: 0x1ed2c50    1

std::atomic_exchange

a: 0x1ed2c50    0
b: 0x1ed2c30    1

a: 0x1ed2c30    1
b: 0x1ed2c30    1

Why is this? Am I doing something wrong? Did I read the documentation incorrectly?

Code listing

#include <iostream>
#include <memory>

int main()
{
    {
        std::cout << "std::atomic_store\n\n";
        auto a = std::make_shared<int>(0);
        auto b = std::make_shared<int>(1);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;

        std::atomic_store(&a, b);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;
    }
    {
        std::cout << "std::atomic_exchange\n\n";
        auto a = std::make_shared<int>(0);
        auto b = std::make_shared<int>(1);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;

        std::atomic_exchange(&a, b);

        std::cout
        << "a: " << a.get() << '\t' << *a << '\n'
        << "b: " << b.get() << '\t' << *b << '\n' << std::endl;
    }
}
+4
source share
4 answers

This description is somewhat misleading.

It says for example

template<class T>
void atomic_store( std::shared_ptr<T>* p,
                   std::shared_ptr<T> r );

"effectively" does p->swap(r). This is true as far as possible (and actually what the standard says).

r - , , . .

+10

std::atomic_exchange a b, a b a.

:

b = std::atomic_exchange(&a, b);

, ( a b), : b, undefined. , , ( ). , ( ).

+2

, " " swap. . , check passess, , . atom_exchange std:: swap.

check-and-set, CAS .

+1

, , , :

    std::atomic_store(
        &b,
        std::atomic_exchange(
            &a,
            b
        )
    );

. a b .

, , .

0

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


All Articles