Does volatile influence non-volatile variables?

前端 未结 4 1836
盖世英雄少女心
盖世英雄少女心 2021-02-20 14:11

Okay, suppose I have a bunch of variables, one of them declared volatile:

int a;
int b;
int c;
volatile int v;

If one thread writes to all four

4条回答
  •  时光取名叫无心
    2021-02-20 14:33

    does that second thread see the values written to a, b and c by the first thread, even though they are not themselves declared volatile? Or can it possibly see stale values?

    You will get stale reads, b/c you can't ensure that the values of a, b, c are the ones set after reading of v. Using state machine (but you need CAS to change the state) is a way to tackle similar issues but it's beyond the scope of the discussion.

    Perhaps this part is unclear, after writing to v and reading first from v, you'd get the right results (non-stale reads), the main issue is that if you do if (v==STATE1){...proceed...}, there is no guarantee some other thread would not be modifying the state of a/b/c. In that case, there will be state reads. If you modify the a/b/c+v once only you'd get the correct result.

    Mastering concurrency and and lock-free structures is a really hard one. Doug Lea has a good book on and most talks/articles of Dr. Cliff Click are a wonderful wealth, if you need something to start digging in.

提交回复
热议问题