Accessing atomic of C++0x as non-atomic

前端 未结 3 1733
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 14:50

I have an atomic variable in my program of type atomic. At some places I don\'t need to access the value in it atomically, as I just check if its 0 o

3条回答
  •  梦毁少年i
    2020-12-19 15:19

    You can't get rid of the atomicity property. But you might be able to reduce some of the overhead involved in the use of atomic variables by relaxing the memory ordering guarantees.

    std::atomic a;
    
    int value = a.load(std::memory_order_relaxed);
    if(value == 0) {
        // blah!
    }
    

    I wouldn't recommend doing this however, and I echo all the comments urging you to avoid this. Are you sure that you're paying a high enough cost for the atomic operations that doing this hack and potentially introducing threading bugs is worth it?

提交回复
热议问题