gpt4 book ai didi

c++ - C++ 条件语句是否带有从条件表达式到语句的依赖关系?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:43:50 26 4
gpt4 key购买 nike

我是专门从内存模型的角度来问的。 http://en.cppreference.com/w/cpp/atomic/memory_order

我问是因为我想知道我是否可以在下面使用 std::memory_order_consume:

mLocalMemPtr1 和 2 以及 mAtomicMemPtr 是指向共享缓冲区的指针。

在我正在做的生产者线程中:

for (int x = 0; x < 10; ++x)
{
++mLocalMemPtr1
*mLocalMemPtr1 = x; // <========= A
mAtomicMemPtr.store(mLocalMemPtr1, std::memory_order_release);
}

在消费者中:

tempMemPtr = mAtomicMemPtr.load(std::memory_order_consume);
while (tempMemPtr != mLocalMemPtr2)
{
++mLocalMemPtr2;
int test = *mLocalMemPtr2; // <======== B
doSomeLongRunningThing(test);
tempMemPtr = mAtomicMemPtr.load(std::memory_order_consume);
}

那么依赖链会去 tempMemPtr -> mLocalMemPtr2 -> test -> doSomeLongRunningThing 吗?

我特别担心 B 可能在 A 之前执行。我知道我可以使用 std::memory_order_acquire,但如果条件语句导致内存顺序依赖,我可以使用 consume(它更轻量级)。

最佳答案

CppReference :

Release-Consume ordering

If an atomic store in thread A is tagged std::memory_order_release and an atomic load in thread B from the same variable is tagged std::memory_order_consume, all memory writes (non-atomic and relaxed atomic) that are dependency-ordered-before the atomic store from the point of view of thread A, become visible side-effects in thread B, that is, once the atomic load is completed, thread B is guaranteed to see everything that thread A wrote to memory if it carries a data dependency into the atomic load.

1.10.10:

An evaluation A is dependency-ordered before an evaluation B if

— A performs a release operation on an atomic object M, and, in another thread, B performs a consume operation on M and reads a value written by any side effect in the release sequence headed by A (...)

1.10.9:

An evaluation A carries a dependency to an evaluation B if - the value of A is used as an operand of B, unless:

— B is an invocation of any specialization of std::kill_dependency (29.3), or

— A is the left operand of a built-in logical AND (&&, see 5.14) or logical OR (||, see 5.15) operator, or

— A is the left operand of a conditional (?:, see 5.16) operator, or

— A is the left operand of the built-in comma (,) operator (5.18); (...)

基于这些事实,我说 mLocalMemPtr2 应该同步。但是仍然存在评估顺序的问题。

if (atomic.load(std::consume) < x)

未指定首先评估哪个。 不能保证(因为我在标准中找不到)编译器将首先执行消费操作,刷新共享缓冲区然后加载atomic 和然后 x

由于没有找到以“希望的”方式评估操作数的证据,我说如果不显式分解原子负载 mLocalMemPtr2 它就不会工作,CPU 可能会读取内存的陈旧值由 mLocalMemPtr2 指向。 memory_order_acquire 在这里不会有太大变化,因为 mLocalMemPtr2 具有数据依赖性。

关于c++ - C++ 条件语句是否带有从条件表达式到语句的依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com