Spin lock operations

For an overview of the spin lock please see: Spin lock: overview.

Spin lock initialization

The spin lock is initialized in the following state:
  • Semaphore count = 0 (maximum = int.MaxValue)
  • Heavy waiter count = 0
  • Lock owner = NO_OWNER

Lock() operation

The following activity diagram illustrates the logic of the lock operation:

mtf-runtime-spinlock-lock.png

When acquiring the lock the following steps occur:
  • The thread id for the thread attempting to take the lock is retrieved using Thread.CurrentThread.ManagedThreadId
  • The number of heavy waiters is incremented in case we block on the semaphore
  • The owner is atomically tested and exchanged with the current thread id
  • The returned previous owner is tested to check that it was NO_OWNER (otherwise another thread got in first)
  • If the previous owner was not NO_OWNER then the thread blocks on the semaphore and the lock acquisition is repeated after a release by another thread occurs
  • If the previous owner was NO_OWNER then the lock is acquired so the number of heavy waiters is decremented and the method returns.

Unlock() operation

The following activity diagram illustrates the logic of the unlock operation:

mtf-runtime-spinlock-unlock.png

The release process simply involves checking that the thread owned the lock and if so setting it back to NO_OWNER (done as an atomic compare-and-exchange) then releasing the heavy waiter semaphore if there were any heavy waiters present.

Last edited Aug 30, 2012 at 11:59 AM by jaorme, version 7

Comments

No comments yet.