Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I atomically read a value in x86 ASM?

I know how to atomically write a value in x86 ASM. But how do I read one? The LOCK prefix can't be used with mov.

To increase a value, I am doing:

lock inc dword ptr Counter

How do I read Counter in a thread-safe way?

like image 721
IamIC Avatar asked Jul 28 '10 04:07

IamIC


1 Answers

As I explain to you in this post:

Accesses to cacheable memory that are split across bus widths, cache lines, and page boundaries are not guaranteed to be atomic by the Intel Core 2 Duo, Intel Core Duo, Pentium M, Pentium 4, Intel Xeon, P6 family, Pentium, and Intel486 processors. The Intel Core 2 Duo, Intel Core Duo, Pentium M, Pentium 4, Intel Xeon, and P6 family processors provide bus control signals that permit external memory subsystems to make split accesses atomic; however, nonaligned data accesses will seriously impact the performance of the processor and should be avoided.

So use:

LOCK        CMPXCHG   EAX, [J]

LOCK CMPXCHG first fence cache memory and than compare the EAX with destination value, if destination value not equ then the result in EAX is destination value.

EDIT: LINKs to:

Intel® 64 and IA-32 Architectures Software Developer’s Manuals

In Volume 3A: System Programming Guide check section 8.1.1

Also check: Optimization Reference Manual section: CHAPTER 7 OPTIMIZING CACHE USAGE

like image 61
GJ. Avatar answered Oct 09 '22 02:10

GJ.