Go Memory Model

happens-before原则
定义:

  • A和B表示多线程执行的两个操作。如果A happens-before B,那么A操作对内存的影响将对执行B的线程(且执行B之前)可见
  • 如果操作A和B在相同的线程中执行,并且A操作的声明在B之前,那么A happens-before B
    注意:
  • happens-before是操作顺序概念,而非时序概念,即
    • A happens-before B并不意味着A在B之前发生
    • A在B之前发生并不意味着A happens-before B
  • happens-before有传递性
    竞态检测:go run -race

Go同步规则

  1. channel的发送 happens-before channel的接收
  2. 关闭channel happens-before 从该Channel接收到最后的返回值0
  3. 不带缓冲的channel的接收 happens-before 相应channel的发送

cover
画师:Nin_n
id:118000020