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?
#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;
}
}
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.
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