Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

According to en.cppreference.com, std::atomic_exchange and std::atomic_store are equivalent to a thread-safe std::swap. But that's not the behavior that I'm getting with g++ or clang++.

Problem live on coliru. (see below)

It 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? Have I misread the documentation?

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;
    }
}
like image 336
caps Avatar asked Dec 08 '22 23:12

caps


1 Answers

That description is somewhat misleading.

It says, e.g.,

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

"effectively" does p->swap(r). Which is true as far as it gets (and is actually what the standard says, too).

But, r is a function argument passed by value, and so is destroyed before the function returns. It doesn't affect anything in the caller.

like image 123
T.C. Avatar answered Dec 25 '22 17:12

T.C.