简体   繁体   中英

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 :

  • will be any trouble when using of == , assignment , read/write instead of (for example) std::atomic_load or exchange statements?
  • is it possible to occur any trouble, something like memory problems while read or write of flag ?
  • is it absolutely safe in any platform with any CPU architecture? I mean(a portable code). because atomic<bool> not need in some X86 architectures?

i just wanna use of atomic feature instead of mutex .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM