是C ++读写int原子吗? [英] Are C++ Reads and Writes of an int Atomic?

查看:105
本文介绍了是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 可以,请参见类模板

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

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