Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Write an int on x86 machine without lock

Tags:

c

concurrency

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?

like image 417
Wei Shi Avatar asked Mar 24 '11 03:03

Wei Shi


1 Answers

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.

like image 128
Hans Passant Avatar answered Oct 13 '22 09:10

Hans Passant