mardi 1 août 2017

C++11 atomic operations: concurrent atomic_fetch_sub_explicit operations

I have a question about the 'atomic_fetch_sub_explicit' operations in c++11. I have run the next code thousands of times, and only observed two possible outputs: "data: 0 1" or "data: 1 0". I want to know is it possible to generate output: "data: 1 1"?

#include <atomic>
#include <thread>

using namespace std;

std::atomic<int> x;
int data1, data2;

void a() { 
    data1 = atomic_fetch_sub_explicit(&x, 1, memory_order_relaxed);
}

void b() {
    data2 = atomic_fetch_sub_explicit(&x, 1, memory_order_relaxed);
}

int main() {
    x = 1;
    std::thread t1(a);
    std::thread t2(b);

    t1.join(), t2.join();
    printf("data: %d %d\n", data1, data2);
}

Aucun commentaire:

Enregistrer un commentaire