[C++] socket - 5 [API事件对象实现线程同步]
/*API事件对象实现线程同步*/ #include<windows.h> #include<stdio.h> DWORD WINAPI myfun1(LPVOID lpParameter);//声明线程函数 DWORD WINAPI myfun2(LPVOID lpParameter); static int a=0; HANDLE hevent;//事件对象 int main() { HANDLE h1,h2;//定义句柄变量 hevent=::CreateEvent(NULL,FALSE,false,NULL); ::SetEvent(hevent); h1=::CreateThread(NULL,0,myfun1,NULL,0,NULL);//创建线程1 printf("线程1开始运行!\r\n"); h2=::CreateThread(NULL,0,myfun2,NULL,0,NULL);//创建线程2 printf("线程2开始运行!\t\n"); ::CloseHandle(h1);//关闭线程句柄对象 ::CloseHandle(h2); ::Sleep(100000); return 0; } DWORD WINAPI myfun1(LPVOID lpParameter)//线程函数 { while(1) { ::WaitForSingleObject(hevent,INFINITE);//请求事件对象 ::ResetEvent(hevent);//设置事件为无信号态 if(a<100) { ::Sleep(1000); a+=1; printf("线程1:%d\r\n",a); ::SetEvent(hevent);//设置事件为有信号态 } else { ::SetEvent(hevent); break; } } return 0; } DWORD WINAPI myfun2(LPVOID lpParameter) { while(1) { ::WaitForSingleObject(hevent,INFINITE); ::ResetEvent(hevent); if(a<100) { ::Sleep(1000); a+=1; printf("线程2:%d\r\n",a); ::SetEvent(hevent); } else { ::SetEvent(hevent); break; } } return 0; }