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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值