同步代码分析
#include <Windows.h>
#include
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 << "1:" << 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)
{
cout << "2:" << g_iCnt-- << endl;
LeaveCriticalSection(&g_CriticalSection);
Sleep(20);
}
else
{
LeaveCriticalSection(&g_CriticalSection);
Sleep(20);
break;
}
}
return 0;
}
运行结果:
心得体会:
互斥是由程序共享资源所引起的,某一个资源不允许同时多个程序访问,当一个进程正在使用资源的时候,其他希望使用该资源的程序必须等待,当该进程使用完并释放资源后,才允许其他进程去访问此资源,此例子也是当线程1获得资源时,线程2必须等待,只有当线程1释放资源时,线程2 方可使用。