利用關鍵程式碼片段實現多線程同步
關鍵程式碼片段又叫臨界區,是指一個小程式碼片段,在代碼能夠執行前,它必須對具有對資源的獨中權。如一次只能一個人打電話的公用電話廳,開始時要建個
電話廳(初始化臨界區:InitializeCriticalSection),一個人打電話(EnterCiticalSection),打完電話離
開,便於別人打(LeaveCriticalSection),電話廳不用時,拆掉,釋放資源(DeleteCriticalSection);如下程式實現多線程同步:#include <windows.h>
#include <iostream>using namespace std;DWORD WINAPI ThreadProc1(
LPVOID lpParameter
);//define a thread function
DWORD WINAPI ThreadProc2(
LPVOID lpParameter
);//define a thread functionint tickets=100;//the total of tickets
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); Sleep(4000);
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;
}WINAPI是函數調用的一種約定,等同於__stdcall,該呼叫慣例規定,按從右至左的順序壓參數入棧,由被調用者把參數彈出棧!