Does volatile influence non-volatile variables?

前端 未结 4 1855
盖世英雄少女心
盖世英雄少女心 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:40

    Yes, volatile write "happens-before" next volatile read on the same variable.

    While @seh is right on about consistency problems with multiple variables, there are use cases that less consistency is required.

    For example, a writer thread updates some state variables; a reader thread displays them promptly. There's not much relation among the variables, we only care about reading the new values promptly. We could make every state variable volatile. Or we could use only one volatile variable as visibility guard.

    However, the saving is only on the paper, performance wise there's hardly any difference. In either version, every state variable must be "flushed" by the writer and "loaded" by the reader. No free lunch.

提交回复
热议问题