mercredi 31 janvier 2018

C++ 11 can you safely pass and access std::atomics by reference in different threads

I am wondering if you can pass a an atomic by reference to a thread and for the .load and .store operations still be thread safe. For instance:

#include <thread>
#include <atomic>
#include <cstdlib>

void addLoop(std::atomic_int& adder)
{
    int i = adder.load();
    std::srand(std::time(0));
    while(i < 200)
    {
        i = adder.load();
        i += (i + (std::rand() % i));
        adder.store(i);
    }
}

void subLoop (std::atomic_int& subber)
{
    int j = subber.load();
    std::srand(std::time(0));
    while(j < 200)
    {
        j = subber.load();
        j -= (j - (std::rand() % j));
        subber.store(j);
    }
}

int main()
{
    std::atomic_int dummyInt(1);
    std::thread add(addLoop, std::ref(dummyInt));
    std::thread sub(subLoop, std::ref(dummyInt));
    add.join();
    sub.join();
    return 0;
}

When the addLoop thread stores the new value into the atomic if subLoop were to access it using the load and store functions would it end up being an undefined state?

Aucun commentaire:

Enregistrer un commentaire