内存模型
定义
Go的内存模型描述的是"在一个groutine中对变量进行读操作能够侦测到在其他goroutine中对该变量的写操作"的条件。
The Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.
happens-before
happens-before通常定义如下:
假设A和B表示一个多线程的程序执行的两个操作。如果A happens-before B,那么A操作对内存的影响将对执行B的线程(且执行B之前)可见。
注意
happens-before并不是指时序关系,不是说A happens-before B就表示操作A在操作B之前发生。具体地说:
A happens-before B并不意味着A在B之前发生;
- A在B之前发生也不意味着
A happens-before B。
A happens-before B并不意味着A在B之前发生
例子
int A = 0;
int B = 0;
void main()
{
A = B + 1; // (1)
B = 1; // (2)
}
根据前面说明的规则,(1) happens-before (2)。但是,如果我们使用gcc -O2编译这个代码,编译器将产生一些指令重排序。有可能执行顺序是这样子的:
- 将B的值取到寄存器
- 将B赋值为1
- 将寄存器值加1后赋值给A
也就是到第二条机器指令(对B的赋值)完成时,对A的赋值还没有完成。换句话说,(1)并没有在(2)之前发生!
A在B之前发生也不意味着A happens-before B