concurrent modification of bits in a integer
I want to know if i attempt to set bits inside a char/integer from multiple thr开发者_如何学Pythoneads, will i lose any modification? I will have all zeros initially and the threads will only set it to 1. The system architecture is x64.
Thanks, Gokul.
On x64 (and x86) operations on ints are atomic. This means that reads and writes are independently atomic, not in combination. (E.g. If you have two threads write an int at the same time, you won't see one half of one and one half of the other -- you will always see one full int or the other.)
However, reading and writing are two separate operations. You can perform some operations interlocked (causing the read and write to be one atomic operation) but I don't believe that bitwise logic falls into the set of operations that can be performed in this manner.
I think you will have to lock on some mutex/monitor and perform the read/write if you want this operation to be atomic.
You must use either a mutex or similar synchronisation mechanism, or an atomic operation. For the former, there are POSIX and Windows libraries readily available and very standard. For the latter, most compilers will provide some functions (e.g. http://gcc.gnu.org/wiki/Atomic), inline assembly mode or other convenient way to use them, and you can always fall back to linking to an object compiled up from assembly language.
You definitely can't avoid such explicit synchronisation. Even if say XOR somehow operated directly and atomically on the value in your CPU cores innermost memory cache (which it doesn't), you need to guarantee that value is synced with other CPU core's caches. Only those CPU instructions that explicitly sync caches are useful to you - it's easiest to use them through one of the library options mentioned above.
精彩评论