#include <windows.h>
#include <process.h> //缺少將出現error C2039: '_beginthreadex' : is not a member of '`global namespace'',
long int one=0,two=0;
CRITICAL_SECTION g_cs;
UINT WINAPI Threahfun(LPVOID lpParam)
{
while(1){
::EnterCriticalSection(&g_cs); //保護共享數據
one++;
two++;
::LeaveCriticalSection(&g_cs);
}
return 0;
}
int main()
{
::InitializeCriticalSection(&g_cs); //初始化臨界區
UINT uID1,uID2;
HANDLE mythread[2]; //聲明句柄數組
mythread[0]=(HANDLE)::_beginthreadex(NULL,0,Threahfun,NULL,0,&uID1); //開始構造新的線程1
mythread[1]=(HANDLE)::_beginthreadex(NULL,0,Threahfun,NULL,0,&uID2); //開始構造新的線程2
Sleep(1000);
::WaitForSingleObject(mythread,INFINITE);
::CloseHandle(mythread[0]); //關閉句柄
::CloseHandle(mythread[1]);
cout<<one<<endl;
cout<<two<<endl;
return 0;
}