volatile 数组的并发更改是原子的并且对所有线程可见吗?

Are concurrent changes on a volatile array atomic and visible to all threads?

在我的应用程序中,我有多个线程访问和修改同一个字符数组。

volatile unsigned char *volatile key[6] = { 0xD4 ,0x32 ,0xF8 ,0x0A ,0x10 ,0xE5 };

volatile unsigned char *volatile保证:

  1. 可见性(所有其他线程将立即看到字符的变化)

  2. Atomicity(任何变化都将由一个线程不间断地执行)

简答:

没有

长答案:

来自GNU C Manual

volatile tells the compiler that the variable is explicitly changeable, and seemingly useless accesses of the variable (for instance, via pointers) should not be optimized away. You might use volatile variables to store data that is updated via callback functions or signal handlers. Sequence Points and Signal Delivery.

这并不意味着带有volatile关键字的变量一定一定会满足您要求的条件。

如果你想要一个数组同时具有 visibilityatomicity你应该使用互斥锁,具体细节当然取决于你的目标。