atomic operator=

when 'return a value' and other threads store the atomic, a race condition will happen?
Hi,
Can you give us more details to better describe your problem?
Atomic objects are not copy assignable.

The overload of operator= which accepts a (non-atomic) value of type T performs an atomic store with std::memory_order_seq_cst
There is no race condition.
Yeah! Store it in atomic way, and then return 'it', if there is a thread is modifying it, the returned value is wrong.
To see the 'current' value of an atomic object (instead of a snapshot of the value at a particular point in time),
alias the atomic object (instead of storing a copy).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <future>

using namespace std::literals ;

std::atomic<int>& foo()
{
    static std::atomic<int> n { 1000 } ;
    return n ;
}

void bar( bool plus )
{
    auto& n = foo() ;

    for( int i = 1 ; i < 200 ; ++i )
    {
        if(plus) { n += i ; std::this_thread::sleep_for( 10ms ) ; }
        else { n -= i ; std::this_thread::sleep_for( 12ms ) ; }
    }
}

int main()
{
    auto future1 = std::async( bar, true ) ;
    auto future2 = std::async( bar, false ) ;

    auto& n = foo() ;
    for( int i = 0 ; i < 10 ; ++i )
    {
        std::cout << n << ' ' << std::flush ;
        std::this_thread::sleep_for( 200ms ) ;
    }
}

http://coliru.stacked-crooked.com/a/f8aed0e7c9b1f310
http://rextester.com/LUQXL35035
Topic archived. No new replies allowed.