public volatile long shared;
and assume further that thread t1 is trying to assign value v1 to shared while t2
is trying to assign it value v2. Is it guaranteed that shared will wind up with either v1
or v2 when the threads finish? Explain.
题目是说看上面那个code,Thread 1 试着给他赋值 v1,Thread 2也试着给他赋值 v2,那两个线程运行结束后,shared 值是不是一定是v1或者v2,为什么?
volatile 关键字确保在编译的时候, 变量不存在任何拷贝, 永远都是取实际的内容。这种情况尤其在中断上下文或者是操作寄存器(和cache一致性有关)时候
一定要使用,否则可能读到的数值是假的或者说没有被更新。
两个线程, 在执行原子操作的条件下, 确定的说, 一定是 v1 或者 v2。
volatile 声明的变量每次都从寄存器里读取 而不是缓存, 如果缓存和寄存器数据不一致经常发生改变,用这种方式声明保证每次读取的数据都是准确的