1. 程式人生 > >25.互斥鎖

25.互斥鎖

creat and ive share std bsp ksh log span

  • 創建互斥鎖
    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 }

25.互斥鎖