Read / write int on X86 machine without lock
Suppose in a C program, I have a p thread running on a 32-bit machine and int Max – a shared 32-bit integer
Each thread can read / write max
Requirement: the value read by the thread should not be corrupted. For example, the first 16 bits and the last 16 bits are out of sync
Question: do I need a lock to protect reading and writing? Or can I safely ignore locking because load / save assembly instructions are guaranteed to occur atomically?
Solution
When ints are properly aligned, reads and writes are atomic It cannot cross the end of a cache line The cache line is 64 bytes Most compilers ensure that alignment is handled, but you can override it with structure packaging compilation instructions
Yes, you need a lock to protect this value when the thread performs read - modify - write operations You can get a cheap one from interlockedxxxx