利用关键代码段实现多线程同步
#include <iostream>
LPVOID lpParameter
);//define a thread function
DWORD WINAPI ThreadProc2(
LPVOID lpParameter
);//define a thread function
HANDLE g_hEvent;//define a handle of event
CRITICAL_SECTION g_cs;//define a ciritical section
int main(int argc,char** argv)
{
HANDLE handle1;//a thread handle
HANDLE handle2;//a thread handle
handle1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);//create a thread
handle2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);//creat a thread
CloseHandle(handle1);//close a thread handle
CloseHandle(handle2);//close a thread handle
InitializeCriticalSection(&g_cs);
DeleteCriticalSection(&g_cs);
return 0;
}
DWORD WINAPI ThreadProc1(
LPVOID lpParameter
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickets>0)
{
Sleep(2);
cout<<"Thread1 Ticket:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}
DWORD WINAPI ThreadProc2(
LPVOID lpParameter
)
{
while(TRUE)
{
EnterCriticalSection(&g_cs);
if(tickets>0)
{
Sleep(2);
cout<<"Thread2 Ticket:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&g_cs);
}
return 0;
}