← 中文资源

简体中文版本

Happens-Before 关系

Happens-Before 定义了线程被保证可见的内存写入,是一切关于可见性与重排序的正确性推理的基础。

阅读英文原文

概念概述

Happens-Before 关系(Happens-Before Relationship)指的是:Happens-Before 定义了线程被保证可见的内存写入,是一切关于可见性与重排序的正确性推理的基础。

从更严格的定义看,Happens-before is a partial ordering between memory operations such that if one operation happens before another, every side effect of the first is visible to the second. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。

为什么需要它

It is invoked whenever reasoning about whether one thread’s writes are seen by another, including via locks, volatile variables, and atomic operations. 它与 Thread-Local Storage、Asynchronous I/O、Goroutine and Task Leaks 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • program order alone guarantees visibility across threads
  • happens-before requires a physical time ordering

需要避免的反模式

  • sharing mutable data without a synchronising edge
  • assuming a compiler or CPU will not reorder independent accesses

实践要点

  1. A lock release and its matching acquire create a happens-before edge, so writes made before the release are visible to any thread that later acquires the same lock.
  2. Without such an edge, the compiler and CPU may reorder or cache writes, so two threads can disagree about memory even when the program order appears correct.
  3. Language memory models define the edges precisely: volatile writes, atomic operations with appropriate ordering, and thread start and join all establish happens-before.

参考来源

https://en.cppreference.com/w/cpp/atomic/memory_order