步骤如下:
1.头文件
2.声明线程函数
3.定义各种变量,包括HANDLE g_hevent;
4.主函数main
5.建立线程 createthread.....
关闭建立的线程句柄
6.建立时间句柄g_hevent,利用createEvent(NULL,FALSE,FALSE,"eventname");
参数1:安全属性,参数2:TRUE为线程释放后事件需要手动设置为无信号,FALSE为线程释放后事件自动设置为无信号,参数3,FALSE为事件初始为无信号状态,TRUE初始为有信号状态。
7.设置事件为有信号状态 利用setevent(g_hevent)
- 线程函数开头部分都是利用WaitForSingleObject(g_hEvent,INFINITE);来等待信号,一旦g_hEvent被setevent设置为有信号,线程函数被释放,由WaitForSingleObject开始执行后面的代码,同时事件被自动设置为无信号状态,该线程函数执行完,需要setevent再次设置为有信号状态,因为其他线程函数的WaitForSingleObject在等待g_hevent事件。代码例子如下:
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
);
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
);
int tickets=1000;
HANDLE g_hEvent;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//g_hEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
g_hEvent=CreateEvent(NULL,FALSE,FALSE,"tickets");
if(g_hEvent)
{
if(ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only instance can run!"<<endl;
return;
}
}
SetEvent(g_hEvent);
// Sleep(80000);
d111: while(tickets ==0){
CloseHandle(g_hEvent);
}
goto d111;
}
DWORD WINAPI Fun1Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(g_hEvent,INFINITE);
// ResetEvent(g_hEvent);
if(tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket : "<<tickets--<<endl;
}
else
break;
SetEvent(g_hEvent);
}
return 0;
}
DWORD WINAPI Fun2Proc(
LPVOID lpParameter // thread data
)
{
while(TRUE)
{
WaitForSingleObject(g_hEvent,INFINITE);
// ResetEvent(g_hEvent);
if(tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket : "<<tickets--<<endl;
}
else
break;
SetEvent(g_hEvent);
}
return 0;
}
网友评论