How is thread synchronization implemented, at the assembly language level?

Posted by Martin on Stack Overflow See other posts from Stack Overflow or by Martin
Published on 2010-03-03T01:13:04Z Indexed on 2010/03/22 1:01 UTC
Read the original article Hit count: 372

While I'm familiar with concurrent programming concepts such as mutexes and semaphores, I have never understood how they are implemented at the assembly language level.

I imagine there being a set of memory "flags" saying:

  • lock A is held by thread 1
  • lock B is held by thread 3
  • lock C is not held by any thread
  • etc

But how is access to these flags synchronized between threads? Something like this naive example would only create a race condition:

  mov edx, [myThreadId]
wait:
  cmp [lock], 0
  jne wait
  mov [lock], edx
  ; I wanted an exclusive lock but the above 
  ; three instructions are not an atomic operation :(

© Stack Overflow or respective owner

Related posts about locking

Related posts about synchronization