If volatile is useless for threading, why do atomic operations require pointers to volatile data?

后端 未结 4 1595
小鲜肉
小鲜肉 2020-12-08 14:37

I\'ve been reading from many sources that the volatile keyword is not helpful in multithreaded scenarios. However, this assertion is constantly challenged by atomic operatio

4条回答
  •  情歌与酒
    2020-12-08 15:11

    It suddenly came to me that I simply misinterpreted the meaning of volatile*. Much like const* means the pointee shouldn't change, volatile* means that the pointee shouldn't be cached in a register. This is an additional constraint that can be freely added: as much as you can cast a char* to a const char*, you can cast an int* to a volatile int*.

    So applying the volatile modifier to the pointees simply ensures that atomic functions can be used on already volatile variables. For non-volatile variables, adding the qualifier is free. My mistake was to interpret the presence of the keyword in the prototypes as an incentive to use it rather than as a convenience to those using it.

提交回复
热议问题