问题描述
C ++内存模型具有放松的原子,不对存储器操作提供任何排序保证。除了我在这里找到的C中的邮箱示例:
The C++ memory model has relaxed atomics, which do not put any ordering guarantees on memory operations. Other than the mailbox example in C which I have found here:
基于本文中的激励示例:
Based on the motivating example in this paper:
我很好奇这种类型的同步机制的其他用例。
I was curious about other use cases for this type of synchronization mechanism.
推荐答案
我在我的工作中经常看到一个统计数据库。如果你
想计算一个事件发生的次数,但不需要任何类型的
同步跨线程,除了使增量安全,使用
memory_order_relaxed
有意义。
A simple example that I see in my work frequently is a stats counter. If youwant to count the number of times an event happens but don't need any sort ofsynchronization across threads aside from making the increment safe, usingmemory_order_relaxed
makes sense.
static std::atomic<size_t> g_event_count_;
void HandleEvent() {
// Increment the global count. This operation is safe and correct even
// if there are other threads concurrently running HandleEvent or
// PrintStats.
g_event_count_.fetch_add(1, std::memory_order_relaxed);
[...]
}
void PrintStats() {
// Snapshot the "current" value of the counter. "Current" is in scare
// quotes because the value may change while this function is running.
// But unlike a plain old size_t, reading from std::atomic<size_t> is
// safe.
const size_t event_count =
g_event_count_.load(std::memory_order_relaxed);
// Use event_count in a report.
[...]
}
需要使用更强的内存顺序。在某些
平台上,这样做可能会对性能产生负面影响。
In both cases, there is no need to use a stronger memory order. On someplatforms, doing so could have negative performance impact.
这篇关于什么是memory_order_relaxed的一些用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!