跳至主要内容

10.临界区

线程安全问题

  • 每个线程都有自己的栈,而局部变量是存储在栈中的,这就意味着每个线程都有一份自己的“局部变量”,如果线程仅仅使用“局部变量”,那么就不存在线程安全问题。如果多个线程公用一个全局变量呢?
  • 线程锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <handleapi.h>
#include <minwinbase.h>
#include <minwindef.h>
#include <processthreadsapi.h>
#include <stdio.h>
#include <synchapi.h>
#include <windows.h>
#include <winnt.h>

int g_dwTickets = 10;
CRITICAL_SECTION cs;

DWORD WINAPI MyFirstThreadProc(LPVOID IpParameter) {
while (1) {
EnterCriticalSection(&cs);
if (g_dwTickets <= 0) {
LeaveCriticalSection(&cs);
break;
}
printf("还有%d张票\n", g_dwTickets);
g_dwTickets--;
printf("卖出去一张,现在还有%d张\n", g_dwTickets);
LeaveCriticalSection(&cs);
}
return 0;
}

int main(int argc, char *argv[]) {
DWORD dwR1,dwR2;
HANDLE aThreadHandles[2];

InitializeCriticalSection(&cs);
aThreadHandles[0] = CreateThread(NULL, 0, MyFirstThreadProc, NULL, 0, NULL);
aThreadHandles[1] = CreateThread(NULL, 0, MyFirstThreadProc, NULL, 0, NULL);
WaitForMultipleObjects(2, aThreadHandles, TRUE, INFINITE);

GetExitCodeThread(aThreadHandles[0], &dwR1);
GetExitCodeThread(aThreadHandles[1], &dwR2);
CloseHandle(aThreadHandles[0]);
CloseHandle(aThreadHandles[1]);
DeleteCriticalSection(&cs);
return 0;
}

关于本文

由 GuQing 撰写,采用 CC BY-NC 4.0 许可协议。