C++ 内存模型具有宽松的原子性,它不对内存操作提供任何顺序保证。除了我在这里找到的 C 语言的邮箱示例之外:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1525.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1525.htm
基于本文的激励示例:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2153.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2153.pdf
我对这种类型的同步机制的其他用例感到好奇。
我在工作中经常看到的一个简单例子是统计计数器。如果你
想要计算事件发生的次数,但不需要任何类型
除了使增量安全之外,还可以使用跨线程同步memory_order_relaxed
说得通。
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.
[...]
}
在这两种情况下,都不需要使用更强的内存顺序。一些
平台,这样做可能会对性能产生负面影响。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)