KSPIN_LOCK my_spinlock = { 0 };
//初始化锁
VOID InitSpinLock()
{
KeInitializeSpinLock(&my_spinlock);
}
VOID safeFunc() {
KIRQL irql;
//获取锁
KeAcquireSpinLock(&my_spinlock,&irql);
//do something
//释放锁
KeReleaseSpinLock(&my_spinlock,irql);
}
使用加锁链表
#include <ntddk.h>
typedef struct _FILE_INFO {
LIST_ENTRY m_ListEntry;
WCHAR m_strFilename[260];
}FILE_INFO,*PFILE_INFO;
KSPIN_LOCK m_list_lock = { 0 };
LIST_ENTRY my_headlist = {0};
VOID MyfileInfoInit() {
InitializeListHead(&my_headlist);
KeInitializeSpinLock(&m_list_lock);
}
VOID Unload(IN PDRIVER_OBJECT DriverObject) {
if (DriverObject!=NULL)
{
KdPrint(("driver unload \r\n"));
DbgPrint("hello kernel currentProcessId = 0x%p\n", PsGetCurrentProcessId());
}
return;
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,IN PUNICODE_STRING RegisteryPath) {
DriverObject->DriverUnload = Unload;
KdBreakPoint();
FILE_INFO my_file_info = { 0 };
//普通操作
InsertHeadList(&my_headlist,(PLIST_ENTRY)&my_file_info);
//使用加锁链表操作
ExInterlockedInsertHeadList(&my_headlist,(PLIST_ENTRY)&my_file_info, &m_list_lock);
//remove
PLIST_ENTRY pRemoveEntry = NULL;
pRemoveEntry = ExInterlockedRemoveHeadList(&my_headlist,&m_list_lock);
return STATUS_SUCCESS;
}
队列自旋锁
和普通自旋锁相比, 队列自旋锁在多CPU平台上具有更好的性能表现,并且遵守“first-come first-served”原则,即:队列自旋锁遵守“谁先等待,谁先获取自旋锁” 的原则 <br /> 队列自旋锁的使用和普通自旋锁的使用方法基本一样,初始化自 旋锁也是使用KeInitializeSpinLock函数,唯一不同的地方是在获取和 释放自旋锁时需要使用新的函数:
//全局
KSPIN_LOCK myQueue_SpinLock = { 0 };
VOID func(){
KeInitializeSpinLock(&myQueue_SpinLock);
KLOCK_QUEUE_HANDLE my_lock_queue_handle;
//do some thing
KeReleaseInStackQueuedSpinLock(&my_lock_queue_handle);
}