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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>