自旋锁,只有全局的自旋锁才有意义.
KeAcquireSpinLock 和 KeReleaseSpinLock 之间的代码只有单线程执行,其他的线程会停留在 KeAcquireSpinLock 等待,知道 KeAcquireSpinLock 被调用.
KSPIN_LOCK my_spin_lock;//定义自旋锁
KIRQL irql; //保存中断级别,因为自旋锁会提升中断级别.
KeInitializeSpinLock(&my_spin_lock);//初始化自旋锁.
void mysafefunction(){
KeAcquireSpinLock(&my_spin_lock,&irql);//开启自旋锁
//这里的代码是单线程的
KeReleaseSpinLock(&my_spin_lock,irql);//结束自旋锁
}
示例:
#include
KSPIN_LOCK my_spin_lock;//定义自旋锁
KIRQL irql; //保存中断级别,因为自旋锁会提升中断级别.
void mysafefunction(UCHAR a){
//这里的代码是单线程的
DbgPrint("misaka:number=%d\r\n", a);
}
VOID DriverUnload(PDRIVER_OBJECT driver){
KeInitializeSpinLock(&my_spin_lock);//初始化自旋锁.
KeAcquireSpinLock(&my_spin_lock, &irql);//开启自旋锁
int a = 0;
while (a < 10){
mysafefunction((UCHAR)a);
a++;
}
KeReleaseSpinLock(&my_spin_lock, irql);//结束自旋锁
}
NTSTATUS DriverEntry(PDRIVER_OBJECT driver, PUNICODE_STRING reg_path){
//驱动入口
UNICODE_STRING str = RTL_CONSTANT_STRING(L"KeAttachProcess");
DbgPrint("misaka: hello world , this is kernel driver ! %x\r\n", (ULONG)MmGetSystemRoutineAddress(&str));
driver->DriverUnload = DriverUnload;
return STATUS_SUCCESS;
}
虽然这个例子没有显示出自旋锁的作用,因为 DriverUnload 是单线程的
Dbgview输出:
misaka: hello world , this is kernel driver ! 3f92530
misaka:number=0
misaka:number=1
misaka:number=2
misaka:number=3
misaka:number=4
misaka:number=5
misaka:number=6
misaka:number=7
misaka:number=8
misaka:number=9