問題描述
我有兩個線程,一個更新一個 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 是原子的嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!