1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| struct Bazard
{
long v;
bool run;
HANDLE startevent,stopevent,threadevent;
};
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
DWORD id=GetCurrentThreadId();
Bazard *pb=(Bazard *)lpParameter;
while (1)
{
WaitForSingleObject(pb->startevent,INFINITE);
if (!pb->run)
break;
pb->v++;
SetEvent(pb->threadevent);
WaitForSingleObject(pb->stopevent,INFINITE);
};
return 0;
}
int main(int argc, char* argv[])
{
const int numThreads=4;
int i;
//create an manual-event used to start and stop all threads
HANDLE startevent=CreateEvent(NULL,TRUE,FALSE,NULL);
HANDLE stopevent=CreateEvent(NULL,TRUE,FALSE,NULL);
//create an auto-reset event for each thread
HANDLE threadevent[numThreads];
for(i=0;i<numThreads;i++)
threadevent[i]=CreateEvent(NULL,FALSE,FALSE,NULL);
//create each thread params
Bazard b[numThreads];
for(i=0;i<numThreads;i++)
{
b[i].run=true;
b[i].startevent=startevent;
b[i].stopevent=stopevent;
b[i].threadevent=threadevent[i];
}
//create threads
DWORD hId[numThreads];
HANDLE ht[numThreads];
for(i=0;i<numThreads;i++)
ht[i]=CreateThread(NULL,120*1024,ThreadProc,&b[i],0,&hId[i]);
//run and control threads
for(i=0;i<numThreads;i++)
b[i].v=10*(i+1);
int c=5;
while(c--)
{
//resume all threads
ResetEvent(stopevent);
SetEvent(startevent);
//wait all thread events
WaitForMultipleObjects(numThreads,threadevent,TRUE,INFINITE);
ResetEvent(startevent);
SetEvent(stopevent);
//analyse each thread work
for(i=0;i<numThreads;i++)
cout << "thread " << i << ": v=" << b[i].v << endl;
}
//allow threads to terminate
for(i=0;i<numThreads;i++)
b[i].run=false;
SetEvent(startevent);
WaitForMultipleObjects(numThreads,ht,TRUE,INFINITE);
//close all handles
for(i=0;i<numThreads;i++)
{
CloseHandle(ht[i]);
CloseHandle(threadevent[i]);
}
CloseHandle(startevent);
CloseHandle(stopevent);
return 0;
} |