Suppose in a C program I have P threads running on a 32 bit machine, and int MAX
--a shared 32-bit integer
Each thread can read/write to MAX.
Requirement: the value a thread read should not be corrupted, e.g first 16bit and last 16bit are out of sync
Question: Do I need a lock to protect the read and write? or Can I safely ignore the lock, because LOAD/SAVE assembly instruction is guaranteed to happen atomically?
Reads and writes are atomic when the int is aligned properly. It cannot straddle the end of a cache line. A cache line is 64 bytes. Most any compiler ensures the alignment is taken care of but it can be overridden with, say, a structure packing pragma.
Yes, you need a lock to protect the value when threads perform a read-modify-write operation. You can get a cheap one from InterlockedXxxx, perhaps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With