Windows Socket programming 3

事件對象實現線程同步

#include<iostream>

#include<windows.h>
#include<stdio.h>
using namespace std;


DWORD WINAPI myfun1(
LPVOID lpParameter
);


DWORD WINAPI myfun2(
LPVOID lpParameter
); 
HANDLE hevent;
int a =0;


int main()
{
HANDLE h1,h2;
hevent=::CreateEvent(NULL,FALSE,false,NULL); // 創建事件
::SetEvent(hevent);
h1=::CreateThread(NULL,0,myfun1,NULL,0,NULL); // 創建線程
cout<<"線程 1 開始運行!"<<endl;
h2=::CreateThread(NULL,0,myfun2,NULL,0,NULL);
cout<<"線程 2 開始運行!"<<endl;
::CloseHandle(h1);
::CloseHandle(h2); // 關閉線程句柄對象
::Sleep(10000);

return 0;
}


DWORD WINAPI myfun1(LPVOID lpParameter) // 線程函數 1 
{
while(1)
{
::WaitForSingleObject(hevent,INFINITE);
::ResetEvent(hevent);
if(a<10000)
{
a+=1;
::Sleep(1000);
cout<<"線程1 :"<<a<<endl;
::SetEvent(hevent); // 設置對象爲無信號狀態
}
else
{
::SetEvent(hevent); // 設置事件對象爲有效對象
break;
}
}
return 0;
}


DWORD WINAPI myfun2(LPVOID lpParameter)
{
while(1)
{
::WaitForSingleObject(hevent,INFINITE);
::ResetEvent(hevent);
if(a<10000)
{
a+=1;
::Sleep(1000);
cout<<"線程2 :"<<a<<endl;
::SetEvent(hevent); 
}
else
{
::SetEvent(hevent); // 設置事件對象爲有效對象
break;
}
}
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章