简体   繁体   English

memory_order_relaxed的使用

[英]Uses of memory_order_relaxed

There are already a few questions on Stackoverflow that essentially ask about the use cases of memory_order_relaxed , such as: Stackoverflow上已经有一些问题主要询问memory_order_relaxed的用例,例如:

Understanding memory_order_relaxed 了解memory_order_relaxed

What are some use cases for memory_order_relaxed memory_order_relaxed有哪些用例

However, I'm still confused about the precise semantics of memory_order_relaxed . 但是,我仍然对memory_order_relaxed的精确语义感到困惑。 Generally, the example use case for memory_order_relaxed is something like std::shared_ptr - basically it keeps an atomic counter, but it doesn't need to sync with other threads. 通常, memory_order_relaxed的示例用例类似于std::shared_ptr - 基本上它保留了原子计数器,但它不需要与其他线程同步。

Okay, so my understanding is as follows: 好的,所以我的理解如下:

std::memory_order_relaxed , when used with load() only guarantees that the thread which loads it will do so atomically - it makes no guarantee about any orderings with respect to other threads that do store() operations on the same variable, and it makes absolutely no guarantee about any loads/stores of non-atomic variables (ie no memory fence will be generated.) std::memory_order_relaxed ,当与load()一起使用时,只保证加载它的线程会以原子方式执行 - 它不保证任何关于对同一变量执行store()操作的线程的任何排序,并且它使得绝对不保证任何非原子变量的加载/存储(即不会生成内存栅栏。)

But does memory_order_relaxed provide ANY sort of "happens-before" type ordering ability, with regard only to the single atomic value? 但是memory_order_relaxed提供了任何类型的“先发生”类型排序能力, 仅关注单个原子值? For example, if we have: 例如,如果我们有:

std::atomic_flag x = ATOMIC_FLAG_INIT;

// Thread A:
//
if (!x.test_and_set(std::memory_order_relaxed)) {
   std::cout << "Thread A got here first!" << std::endl;
}

// Thread B:
//
if (!x.test_and_set(std::memory_order_relaxed)) {
   std::cout << "Thread B got here first!" << std::endl;
}

In the above example, even though we used memory_order_relaxed , haven't we also provided a guaranteed way to reason about ordering here? 在上面的例子中,即使我们使用了memory_order_relaxed ,我们还没有提供一种保证的方式来推理这里的订购吗? In other words, both Thread A and Thread B will be able to reason about which thread set the flag first. 换句话说,线程A和线程B都能够推断出哪个线程首先设置了标志。 It's just that, due to the relaxed ordering, neither thread A nor thread B will be able to assume anything about the values of any surrounding non-atomic shared variables, since there is no memory fence. 只是由于放松的顺序,线程A和线程B都不能假设任何周围的非原子共享变量的值,因为没有内存栅栏。 Or am I incorrect here? 或者我在这里不正确?

You're correct. 你说的没错。 And as you noted, there are use cases (such as a counter) where that's fine. 正如您所指出的,有一些用例(例如计数器),这很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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