user6552457
user6552457

Reputation:

Using compare and read/write operations for std::atomic<bool> in c++?

Assume there are 2 threads as threadA and threadB and we're gonna using of a std::atomic<bool> data-type in these threads. So now we have some critical sections as bellow:

My global variable (threads access to it concurrently) :

std::atomic<bool> flag;

threadA :

void *threadA(void *arg)
{
    bool ttt = true;
    if(flag == true)                   // comparison operator ==
        // do something

    // something to do
    flag = false;                      // assign a avalue
    ttt = flag;                        // read operation

    return 0;
}

threadB :

void *threadB(void *arg)
{
    bool m = true;
    if(flag == true)                   // comparison operator ==
        flag = false;

    // something to do
    flag = true;                       // assign a value
    m = !flag;                         // read operation

    return 0;
}

Any way, i know std::atomic<> unlike ordinary data-types are free-races, but i wanna be sure about these :

i just wanna use of atomic feature instead of mutex.

Upvotes: 2

Views: 1221

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136218

will be any trouble when using of ==, assignment, read/write instead of (for example) std::atomic_load or exchange statements?

When operator== is used with std::atomic<T> and T, it first invokes atomic<T>::operator T() to load the atomic value using the strongest memory ordering std::memory_order_seq_cst. Next, operator==(T, T) is used. This sequence is not atomic. Which means that when the comparison actually happens that std::atomic<T> may have already changed.

just wanna use of atomic feature instead of mutex.

You can implement a spin-lock with an atomic using std::atomic::compare_exchange_weak (there is an example), but it won't be able to put the thread to sleep like std::mutex does.

Upvotes: 1

Related Questions