一些特定用例的C ++原子存储顺序

use*_*513 5 c++ multithreading thread-safety compare-and-swap stdatomic

在下一种情况下,我将a atomic<uint64_t>用作计数器,并从5个或更多线程中对其进行递增,并在递增之前使用该值来做出一些决定。

atomic<uint64_t> global_counter;

void thread_funtion(){
    uint64_t local_counter = global_counter.fetch_add(1,std::memory_order_relaxed);
    if(local_counter == 24)
       do_somthing(local_counter);
}
Run Code Online (Sandbox Code Playgroud)

thread_funtion()将由5个不同的线程执行。一旦我知道了,local_counter我的代码就不再关心global_counterthread_funtion()运行时是否再次进行更改(业务逻辑的方式是每次thread_function()调用仅需要一个唯一的递增值)。

std::memory_order_relaxed安全的,在这种情况下使用?

ala*_*ain 7

memory_order_relaxed 保证原子执行,但仅此而已。

使用memory_order_relaxed,将只有一个线程在调用do_something(),因为因为这fetch_add是对的唯一操作global_counter,并且是原子执行的,所以24必须恰好一次达到该值。但是不能保证它将是哪个线程。

  • @ user1934513,C ++标准说明了所有内容:`用值和arg的算术加法结果原子替换当前值。使用锁,CAS循环等来实现 (2认同)