gpt4 book ai didi

c++ - 对共享数据的线程安全访问 - 实际发生读/写并且不会发生重新排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:55:09 25 4
gpt4 key购买 nike

来自这里:https://stackoverflow.com/a/2485177/462608

For thread-safe accesses to shared data, we need a guarantee that
the read/write actually happens (that the compiler won't just store the value in a register instead and defer updating main memory until much later)
that no reordering takes place. Assume that we use a volatile variable as a flag to indicate whether or not some data is ready to be read. In our code, we simply set the flag after preparing the data, so all looks fine. But what if the instructions are reordered so the flag is set first?

  • 在哪些情况下,编译器会将值存储在寄存器中并推迟更新主内存? [关于上述引述]
  • 上面引述的“重新排序”是什么意思?在什么情况下会发生?

最佳答案

问:在哪些情况下,编译器会将值存储在寄存器中并延迟更新主内存?

答:(这是一个广泛的开放式问题,可能不太适合 stackoverflow 格式。)简短的回答是,只要源语言的语义(C++ per你的标签)允许它并且编译器认为它是有利可图的。

问:上面引述的“重新排序”是什么?

答:编译器和/或 CPU 发出加载和存储指令的顺序不同于原始程序源的一对一翻译所指示的顺序。

问:在什么情况下会发生?

答:对于编译器来说,类似于第一个问题的答案,任何时候原始程序语义允许,编译器认为有利可图。对于 CPU,它是相似的,CPU 通常可以根据架构内存模型重新排序内存访问,只要原始(单线程!)结果相同即可。例如,编译器和 CPU 都可以尝试尽早提升负载,因为加载延迟通常对性能至关重要。

为了执行更严格的排序,例如为了实现同步原语,CPU 提供了各种atomic 和/或fence 指令,编译器可能会根据编译器和源语言提供禁止重新排序的方法。

关于c++ - 对共享数据的线程安全访问 - 实际发生读/写并且不会发生重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10780728/

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