views:

58

answers:

2

I can't find any function to acquire spinlock in Win32 Apis.
Is there a reason?

When I need to use spinlock, what do I do?

I know there is an CriticalSectionAndSpinCount funtion.
But that's not what I want.

Edit:
I want to synchronize a memory which will be shared between kernel space and user space. -The memory will be mapped.
I should lock it when I access the data structure and the locking time will be very short.
The data structure(suppose it is a queue) manages event handles to interaction each other.
What synchronization mechanism should I use?

+4  A: 

A spinlock is clearly not appropriate for user-level synchronization. From http://www.microsoft.com/whdc/driver/kernel/locks.mspx:

All types of spin locks raise the IRQL to DISPATCH_LEVEL or higher. Spin locks are the only synchronization mechanism that can be used at IRQL >= DISPATCH_LEVEL. Code that holds a spin lock runs at IRQL >= DISPATCH_LEVEL, which means that the system’s thread switching code (the dispatcher) cannot run and, therefore, the current thread cannot be pre-empted.

Imagine if it were possible to take a spin lock in user mode: Suddenly the thread would not be able to be pre-empted. So on a single-cpu machine, this is now an exclusive and real-time thread. The user-mode code would now be responsible for handling interrupts and other kernel-level tasks. The code could no longer access any paged memory, which means that the user-mode code would need to know what memory is currently paged and act accordingly. Cats and dogs living together, mass hysteria!

Perhaps a better question would be to tell us what you are trying to accomplish, and ask what synchronization method would be most appropriate.

Philip Rieck
Thanks Philips. I've edited my question.
Benjamin
A: 

There is a managed user-mode SpinLock as described here. Handle with care, as advised in the docs - it's easy to go badly wrong with these locks.

The only way to access this in native code is via the Win32 API you named already - CriticalSectionAndSpinCount and its siblings.

Steve Townsend