本文介绍了是C ++读取和写入int原子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程,一个更新一个int和一个读取它。这个值是一个统计数据,读和写的顺序是不相关的。

I have two threads, one updating an int and one reading it. This value is a statistic where the order of the read and write 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.

例如,考虑

value = ox0000FFFF
将值增加到0x00010000

value = ox0000FFFFincrement value to 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 is

我总是同步这些类型的访问,但很好奇社区的想法。

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

推荐答案

首先可能认为本机机器大小的读写是原子的,但是有很多问题要处理,包括缓存一致性在处理器/核之间。在Windows上使用原子操作,如Interlocked *,在Linux上使用原子操作。 C ++ 0x将有一个原子模板来包装在一个漂亮的跨平台接口。现在如果你使用平台抽象层,它可以提供这些功能。 可以查看类模板。

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原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:54