32位与64位原子操作的问题

这是微软介绍The Interlocked API的部分,不过里面讲到了原子操作的问题,虽然应该只是针对微软操作系统,不过我倒是觉得所有操作系统应该是一致的。
对CPU位数相同或低于CPU位数且字节对齐的一个数值操作,应该可以完成赋值取值操作,赋值后该数一定为要赋的值,取值后取到的也一定是该值被赋的一个值,都不会出现中间值。
所以最终觉得32位整数,倘若保证只有一个线程会写值,其他线程读值,是不可能会出错的。
倘若多线程读写,不过倘若多线程只是用它作为一个bool值,且通过bool值通知而已,又不在乎多线程相应,我觉得这样用也不应没有什么不可以的。
 
Interlocked Variable Access

Applications must synchronize access to variables that are shared by multiple threads. Applications must also ensure that operations on these variables are performed atomically (performed in their entirety or not at all.)

Simple reads and writes to properly-aligned 32-bit variables are atomic operations. In other words, you will not end up with only one portion of the variable updated; all bits are updated in an atomic fashion. However, access is not guaranteed to be synchronized. If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation.

Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.

原文地址:https://www.cnblogs.com/dongzhiquan/p/2992465.html