- 创建互斥锁
1 SRWLOCK g_lock;
注意一个线程仅能锁定资源一次,不能多次锁定资源
- 读取期间锁定数据,数据无法被外部线程修改
1 AcquireSRWLockShared(&g_lock);
- 释放互斥锁
1 AcquireSRWLockShared(&g_lock);
完整代码:(一个进程读,是个进程写,读的时候不能写,写的时候不能读)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <Windows.h> 4 5 int num = 6400000; 6 SRWLOCK g_lock; 7 // 注意一个线程仅能锁定资源一次,不能多次锁定资源 8 DWORD WINAPI read(void*p) 9 { 10 AcquireSRWLockShared(&g_lock);//读取期间,锁定数据,数据无法被修改 11 int i = 0; 12 while (1) 13 { 14 Sleep(1000); 15 printf("\n第%d秒num=%d",i, num); 16 17 if (i==20) 18 { 19 break; 20 } 21 i++; 22 } 23 ReleaseSRWLockShared(&g_lock); 24 25 } 26 27 //写数据 28 DWORD WINAPI write(void *p) 29 { 30 AcquireSRWLockExclusive(&g_lock);//锁定写入, 31 printf("\n开始写入"); 32 for (int i = 0; i < 100000; i++) 33 { 34 num--; 35 } 36 ReleaseSRWLockExclusive(&g_lock);// 37 printf("\n结束写入"); 38 39 } 40 41 42 void main() 43 { 44 InitializeSRWLock(&g_lock);//初始化 45 46 47 CreateThread(NULL, 0, read, NULL, 0, NULL); 48 49 50 HANDLE hd[64]; 51 for (int i = 0; i < 64; i++) 52 { 53 hd[i] = CreateThread(NULL, 0, write, NULL, 0, NULL); 54 } 55 56 WaitForMultipleObjects(64, hd, TRUE, INFINITE); 57 58 printf("\n last=%d", num); 59 60 61 62 63 64 65 66 system("pause"); 67 }