Why is volatile not considered useful in multithreaded C or C++ programming?

前端 未结 9 2050
予麋鹿
予麋鹿 2020-11-21 21:01

As demonstrated in this answer I recently posted, I seem to be confused about the utility (or lack thereof) of volatile in multi-threaded programming contexts.<

9条回答
  •  长情又很酷
    2020-11-21 21:30

    Your understanding really is wrong.

    The property, that the volatile variables have, is "reads from and writes to this variable are part of perceivable behaviour of the program". That means this program works (given appropriate hardware):

    int volatile* reg=IO_MAPPED_REGISTER_ADDRESS;
    *reg=1; // turn the fuel on
    *reg=2; // ignition
    *reg=3; // release
    int x=*reg; // fire missiles
    

    The problem is, this is not the property we want from thread-safe anything.

    For example, a thread-safe counter would be just (linux-kernel-like code, don't know the c++0x equivalent):

    atomic_t counter;
    
    ...
    atomic_inc(&counter);
    

    This is atomic, without a memory barrier. You should add them if necessary. Adding volatile would probably not help, because it wouldn't relate the access to the nearby code (eg. to appending of an element to the list the counter is counting). Certainly, you don't need to see the counter incremented outside your program, and optimisations are still desirable, eg.

    atomic_inc(&counter);
    atomic_inc(&counter);
    

    can still be optimised to

    atomically {
      counter+=2;
    }
    

    if the optimizer is smart enough (it doesn't change the semantics of the code).

提交回复
热议问题