#include <Windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI Thread1(LPVOID lpParmeter);
DWORD WINAPI Thread2(LPVOID lpParmeter);
CRITICAL_SECTION g_CriticalSection; // 定义
static int g_iCnt = 100;
int main()
{
HANDLE hThread1 = INVALID_HANDLE_VALUE;
HANDLE hThread2 = INVALID_HANDLE_VALUE;
InitializeCriticalSection(&g_CriticalSection); // 初始化
hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);
Sleep(4000); // 让2个线程有足够的时间执行完操作。
CloseHandle(hThread1);
CloseHandle(hThread2);
DeleteCriticalSection(&g_CriticalSection); // 删除
system("PAUSE");
return 0;
}
DWORD WINAPI Thread1(LPVOID lpParmeter)
{
while (true)
{
EnterCriticalSection(&g_CriticalSection); // 进入临界区,获得所有权,其他线程就等待
if (g_iCnt > 0)
{
//Sleep(20);
cout << "Thread1:" << g_iCnt-- << endl;
LeaveCriticalSection(&g_CriticalSection); // 离开临界区,释放所有权
Sleep(20);
}
else
{
LeaveCriticalSection(&g_CriticalSection);
Sleep(20);
break;
}
}
return 0;
}
DWORD WINAPI Thread2(LPVOID lpParameter)//thread data
{
while (true)
{
EnterCriticalSection(&g_CriticalSection);
if (g_iCnt > 0)
{
//Sleep(20);
cout << "thread2:" << g_iCnt-- << endl;
LeaveCriti
calSection(&g_CriticalSection);
Sleep(20);
}
else
{
LeaveCriticalSection(&g_CriticalSection);
Sleep(20);
break;
}
}
return 0;
}
运行结果:
Thread1:100
thread2:99
Thread1:98
thread2:97
thread2:96
Thread1:95
thread2:94
Thread1:93
thread2:92
Thread1:91
thread2:90
Thread1:89
thread2:88
Thread1:87
thread2:86
Thread1:85
Thread1:84
thread2:83
Thread1:82
thread2:81
thread2:80
Thread1:79
thread2:78
Thread1:77
thread2:76
Thread1:75
Thread1:74
thread2:73
thread2:72
Thread1:71
thread2:70
Thread1:69
Thread1:68
thread2:67
thread2:66
Thread1:65
thread2:64
Thread1:63
thread2:62
Thread1:61
thread2:60
Thread1:59
thread2:58
Thread1:57
thread2:56
Thread1:55
thread2:54
Thread1:53
thread2:52
Thread1:51
thread2:50
Thread1:49
thread2:48
Thread1:47
thread2:46
Thread1:45
thread2:44
Thread1:43
thread2:42
Thread1:41
thread2:40
Thread1:39
thread2:38
Thread1:37
thread2:36
Thread1:35
thread2:34
Thread1:33
thread2:32
Thread1:31
thread2:30
Thread1:29
thread2:28
Thread1:27
thread2:26
Thread1:25
thread2:24
Thread1:23
thread2:22
Thread1:21
thread2:20
Thread1:19
thread2:18
Thread1:17
thread2:16
Thread1:15
thread2:14
Thread1:13
thread2:12
Thread1:11
thread2:10
Thread1:9
thread2:8
Thread1:7
thread2:6
Thread1:5
thread2:4
Thread1:3
thread2:2
Thread1:1
请按任意键继续. . .
Process returned 0 (0x0) execution time : 38.045 s
Press any key to continue.
心得总结:线程1与线程2存在互斥关系,线程1获得资源,线程2只能等待;只有线程1释放资源后线程2才能获得资源并使用资源。
网友评论