C++ 对 int 的读写是原子的吗?

Are C++ Reads and Writes of an int Atomic?(C++ 对 int 的读写是原子的吗?)
本文介绍了C++ 对 int 的读写是原子的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程,一个更新一个 int,一个读取它.这是一个与读写顺序无关的统计值.

I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.

我的问题是,我是否需要同步访问这个多字节值?或者,换一种说法,可以部分写入完成并被中断,然后再进行读取.

My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read happen.

例如,考虑一个值 = 0x0000FFFF,它的增量值为 0x00010000.

For example, think of a value = 0x0000FFFF that gets incremented value of 0x00010000.

是否存在我应该担心的值看起来像 0x0001FFFF 的时间?当然,类型越大,发生这种情况的可能性就越大.

Is there a time where the value looks like 0x0001FFFF that I should be worried about? Certainly the larger the type, the more possible something like this to happen.

我一直同步这些类型的访问,但很好奇社区的想法.

I've always synchronized these types of accesses, but was curious what the community thinks.

推荐答案

起初可能会认为本机机器大小的读写是原子的,但有许多问题需要处理,包括处理器/内核之间的缓存一致性.在 Windows 上使用 Interlocked* 等原子操作,在 Linux 上使用等效操作.C++0x 将有一个原子"模板来将它们包装在一个漂亮的跨平台界面中.目前,如果您使用平台抽象层,它可能会提供这些功能.ACE 可以,请参阅类模板 ACE_Atomic_Op.

At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a nice and cross-platform interface. For now if you are using a platform abstraction layer it may provide these functions. ACE does, see the class template ACE_Atomic_Op.

这篇关于C++ 对 int 的读写是原子的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)