Saturday, February 14, 2009

Queued Spin Locks- Spinning with discipline!

Most of you know about spin locks and yet many of you might not know about queued spin locks. Queued spin locks are available from Windows XP onwards. They are more efficient than the traditional spin locks. There are two advantages that queued spin locks offer:

  1. If multiple threads request the same lock, the threads are queued in the order of their request.
  2. Queued spin locks test and set a variable that is local to the current CPU, and hence generate less bus traffic.


 

How to use queued spin locks?


 

KSPIN_LOCK             qsl;

KLOCK_QUEUE_HANDLE    qh;

KeinitializeSpinLock( &qsl );

KeAcquireInStackQueuedSpinLock( &qsl, &qh );

// Do some work… Don't take too long.

// Remember that you are holding a spin lock

KeReleaseInStackQueuedSpinLock( &qh );


 

As opposed to KeAcquireSpinLock, the caller of KeAcquireInStackQueuedSpinLock does not need to store the current IRQL. This is automatically stored in the KLOCK_QUEUE_HANDLE structure when a call to KeAcquireInStackQueuedSpinLock is made.

Ah! One more thing: Don't ever use KeAcquireSpinLock and KeAcquireInStackQueuedSpinLock on the same spin lock!

No comments:

Post a Comment