Windows线程(使用Event同步)
Windows线程(使用Event同步) 佟强 2008.10.9
- #include <stdio.h>
- #include <windows.h>
- //线程函数
- DWORD WINAPI MyThreadProc(LPVOID lpParameter);
- //用户定义的类
- class MyThreadParam{
- public:
- void myfunc();
- };
- HANDLE ev; //事件句柄
- int main(int argc,char* argv[]){
- DWORD myThreadID; //线程ID
- MyThreadParam threadParam; //线程参数,可以传递任何类型的指针
- HANDLE h; //线程句柄
- //创建事件,初始为无信号,手工重置
- ev = CreateEvent(NULL,TRUE,FALSE,"MyEventName");
- h = CreateThread(NULL, //线程属性
- 0, //stack大小,0使用默认堆栈大小
- MyThreadProc, //线程函数
- &threadParam, //线程参数,LPVOID类型
- 0, //线程标志
- &myThreadID //线程ID,输出值
- );
- printf("Thread ID is %d/n",myThreadID);
- //等待事件有信号,即等待线程结束
- WaitForSingleObject(ev,INFINITE);
- printf("Thread %d terminated!/n",myThreadID);
- //重置信号为无信号
- ResetEvent(ev);
- return 0;
- }
- DWORD WINAPI MyThreadProc(LPVOID lpParameter){
- MyThreadParam *param = (MyThreadParam*)lpParameter;
- for(int i=0; i<10; i++){
- param->myfunc();
- }
- //置事件为有信号
- SetEvent(ev);
- return 0;
- }
- void MyThreadParam::myfunc(){
- printf("Hello Thread!/n");
- }