gpt4 book ai didi

c++11 注册缓存线程安全

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

volatile: The Multithreaded Programmer's Best Friend , Andrei Alexandrescu 给出了这个例子:

class Gadget
{
public:
void Wait()
{
while (!flag_)
{
Sleep(1000); // sleeps for 1000 milliseconds
}
}
void Wakeup()
{
flag_ = true;
}
...
private:
bool flag_;
};

他说,

... the compiler concludes that it can cache flag_ in a register ... it harms correctness: after you call Wait for some Gadget object, although another thread calls Wakeup, Wait will loop forever. This is because the change of flag_ will not be reflected in the register that caches flag_.

然后他提供了一个解决方案:

If you use the volatile modifier on a variable, the compiler won't cache that variable in registers — each access will hit the actual memory location of that variable.

现在,其他人在 stackoverflow 和其他地方提到 volatile 关键字并没有真正提供任何线程安全保证,我应该改用 std::atomic 或 mutex 同步,我同意这一点。

然而,以 std::atomic 路线为例,它在内部使用内存栅栏 read_acquire 和 write_release ( Acquire and Release Semantics ),我看不出它实际上是如何修复寄存器缓存问题的。

例如,在 x86 的情况下,x86/64 上的每个加载都已经暗示了获取语义,每个存储都暗示了释放语义,这样在 x86 下编译的代码根本不会发出任何实际的内存屏障。 ( The Purpose of memory_order_consume in C++11 )

g = Guard.load(memory_order_acquire);
if (g != 0)
p = Payload;

enter image description here

On Intel x86-64, the Clang compiler generates compact machine code for this example – one machine instruction per line of C++ source code. This family of processors features a strong memory model, so the compiler doesn’t need to emit special memory barrier instructions to implement the read-acquire.

所以....现在假设x86 arch,std::atomic 如何解决注册表中的缓存问题?在编译代码中没有用于读取获取的内存屏障指令,它似乎与仅用于常规读取的编译代码相同。

最佳答案

您是否注意到代码中的一个寄存器没有加载? _Guard 有显式内存加载。所以它实际上阻止了寄存器中的缓存。

现在它如何做到这一点取决于特定平台对 std::atomic 的实现,但它必须这样做。

顺便说一句,Alexandrescu 的推理对于现代平台来说是完全错误的。虽然 volatile 确实会阻止编译器在寄存器中进行缓存,但它不会阻止 CPU 或硬件进行类似的缓存。在某些平台上,它可能恰好就足够了,但绝对没有理由编写可能会在未来的 CPU、编译器、库或平台上出现故障的无偿不可移植代码,因为完全可移植的替代方案是现成的。

关于c++11 注册缓存线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32496236/

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