您的位置:首页 > 其它

线程同步:CriticalSection关键区域

2009-05-28 11:40 288 查看
#include <Windows.h>
#include <iostream>
using namespace std;

DWORD WINAPI Func1Proc(
LPVOID lpParameter
);
DWORD WINAPI Func2Proc(
LPVOID lpParameter
);

int tickets = 100;
CRITICAL_SECTION g_cs;
int main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1 = CreateThread(NULL, 0, Func1Proc, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Func2Proc, NULL, 0, NULL);

CloseHandle(hThread1);
CloseHandle(hThread2);

InitializeCriticalSection(&g_cs);
Sleep(2000);

DeleteCriticalSection(&g_cs);
return 0;
}

DWORD WINAPI Func1Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if (tickets > 0)
{
Sleep(10);
cout << "thread1 sell ticket : " << tickets-- << endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}

DWORD WINAPI Func2Proc(
LPVOID lpParameter
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if (tickets > 0)
{
Sleep(10);
cout << "thread2 sell ticket : " << tickets-- << endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: