reordering issue in a multiprocessor environment

reordering issue in a multiprocessor environment

I want to perform an atomic 'and' operation on IA-32.

Please consider the following situation:
; processor 0
lea edx, var
mov ecx, mask
mov eax, [edx]
lock and [edx], ecx

; processor 1
lea edx, var
mov eax, 0xff
xchg [edx], eax

I'm not sure if it's possible that the store to 'var' by processor 1 can or cannot occure between the load and the store to 'var' by processor 0.
So, is this working or do I need to spin lock like this:

; processor 0
push ebx
lea edx, var
mov ecx, mask
@@loop:
mov ebx, [edx]
mov eax, ebx
and eax, ecx
lock cmpxchg [edx], eax
cmp eax, ebx
jne @@loop
pop ebx

Thanks for any answer. Best tegards.

2 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

Hi - the value of [edx] can definitely be changed by an external agent between 'MOV eax, [edx]' and 'AND [edx], ecx' (with or without 'LOCK').

Memory ordering is a complex topic, one is strongly advised to read about before implementing similar constructions, mainly because many seemingly natural assumptions don't work in practice. Intel SDM Vol 3A, Chapter8. If you have not yet.

Now, IFF you need to have the value of [edx] before or after applying 'AND' you do need a loop with CMPXCHG as you have shown, otherwise just LOCK AND works to perform operation properly, and ensures proper prior memory operations serialization.

Regards,
-Max

Leave a Comment

Please sign in to add a comment. Not a member? Join today