易挥发,使在C / C ++的原子一个字节一个适当的方式? [英] Is volatile a proper way to make a single byte atomic in C/C++?

查看:114
本文介绍了易挥发,使在C / C ++的原子一个字节一个适当的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,挥发性不会对INT例如强制原子性,但它如果你访问一个字节?语义要求写入和读取从内存中始终如果我没有记错。

I know that volatile does not enforce atomicity on int for example, but does it if you access a single byte? The semantics require that writes and reads are always from memory if I remember correctly.

或者换句话说:是否CPU的读取和写入字节总是原子

Or in other words: Do CPUs read and write bytes always atomically?

推荐答案

不仅标准别提原子什么,但你很可能连问错了问题。

Not only does the standard not say anything about atomicity, but you are likely even asking the wrong question.

典型的CPU读取和写入原子单字节。问题来了,因为当你有多个内核,并非所有的内核将看到字节为已在同一时间写的。事实上,它可能是相当长的一段时间(以指令(又名,微秒或者毫秒)CPU说话,数千或数百万)所有内核都看到了写了。

CPUs typically read and write single bytes atomically. The problem comes because when you have multiple cores, not all cores will see the byte as having been written at the same time. In fact, it might be quite some time (in CPU speak, thousands or millions of instructions (aka, microseconds or maybe milliseconds)) before all cores have seen the write.

所以,你需要有点名不副实的C ++ 0x的原子操作。他们使用CPU指令,以确保事物的秩序没有得到搞砸了,而当其它内核看你写后,你写的价值,他们看到了新的价值,而不是旧的。他们的工作是不能操作的这么多原子准确,但要确保适当的同步步骤也发生了。

So, you need the somewhat misnamed C++0x atomic operations. They use CPU instructions that ensure the order of things doesn't get messed up, and that when other cores look at the value you've written after you've written it, they see the new value, not the old one. Their job is not so much atomicity of operations exactly, but making sure the appropriate synchronization steps also happen.

这篇关于易挥发,使在C / C ++的原子一个字节一个适当的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆