1. KSPIN_LOCK my_spinlock = { 0 };
  2. //初始化锁
  3. VOID InitSpinLock()
  4. {
  5. KeInitializeSpinLock(&my_spinlock);
  6. }
  7. VOID safeFunc() {
  8. KIRQL irql;
  9. //获取锁
  10. KeAcquireSpinLock(&my_spinlock,&irql);
  11. //do something
  12. //释放锁
  13. KeReleaseSpinLock(&my_spinlock,irql);
  14. }

使用加锁链表

  1. #include <ntddk.h>
  2. typedef struct _FILE_INFO {
  3. LIST_ENTRY m_ListEntry;
  4. WCHAR m_strFilename[260];
  5. }FILE_INFO,*PFILE_INFO;
  6. KSPIN_LOCK m_list_lock = { 0 };
  7. LIST_ENTRY my_headlist = {0};
  8. VOID MyfileInfoInit() {
  9. InitializeListHead(&my_headlist);
  10. KeInitializeSpinLock(&m_list_lock);
  11. }
  12. VOID Unload(IN PDRIVER_OBJECT DriverObject) {
  13. if (DriverObject!=NULL)
  14. {
  15. KdPrint(("driver unload \r\n"));
  16. DbgPrint("hello kernel currentProcessId = 0x%p\n", PsGetCurrentProcessId());
  17. }
  18. return;
  19. }
  20. NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,IN PUNICODE_STRING RegisteryPath) {
  21. DriverObject->DriverUnload = Unload;
  22. KdBreakPoint();
  23. FILE_INFO my_file_info = { 0 };
  24. //普通操作
  25. InsertHeadList(&my_headlist,(PLIST_ENTRY)&my_file_info);
  26. //使用加锁链表操作
  27. ExInterlockedInsertHeadList(&my_headlist,(PLIST_ENTRY)&my_file_info, &m_list_lock);
  28. //remove
  29. PLIST_ENTRY pRemoveEntry = NULL;
  30. pRemoveEntry = ExInterlockedRemoveHeadList(&my_headlist,&m_list_lock);
  31. return STATUS_SUCCESS;
  32. }

队列自旋锁

  1. 和普通自旋锁相比, 队列自旋锁在多CPU平台上具有更好的性能表现,并且遵守“first-come first-served”原则,即:队列自旋锁遵守“谁先等待,谁先获取自旋锁” 的原则 <br /> 队列自旋锁的使用和普通自旋锁的使用方法基本一样,初始化自 旋锁也是使用KeInitializeSpinLock函数,唯一不同的地方是在获取和 释放自旋锁时需要使用新的函数:
  1. //全局
  2. KSPIN_LOCK myQueue_SpinLock = { 0 };
  3. VOID func(){
  4. KeInitializeSpinLock(&myQueue_SpinLock);
  5. KLOCK_QUEUE_HANDLE my_lock_queue_handle;
  6. //do some thing
  7. KeReleaseInStackQueuedSpinLock(&my_lock_queue_handle);
  8. }