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
| #include "windows.h"
#include <iostream>
using namespace std;
#define NB_THREADS 4
struct ThreadsMarker
{
ThreadsMarker()
{
finishedThreads = new bool[4];
for(int i=0; i<NB_THREADS; i++)
finishedThreads[i] = false;
}
~ThreadsMarker(){delete [] finishedThreads;}
bool* finishedThreads;
} ;
DWORD WINAPI func0( LPVOID lpParam )
{
for (int i=0; i<5; i++)
{
cout << "func0" << endl;
Sleep(500);
}
ThreadsMarker* tm = reinterpret_cast<ThreadsMarker*>(lpParam);
tm->finishedThreads[0] = true;
cout << "func0 finished" << endl;
return 0;
}
DWORD WINAPI func1( LPVOID lpParam )
{
for (int i=0; i<5; i++)
{
cout << "func1" << endl;
Sleep(480);
}
ThreadsMarker* tm = reinterpret_cast<ThreadsMarker*>(lpParam);
tm->finishedThreads[1] = true;
cout << "func1 finished" << endl;
return 0;
}
DWORD WINAPI func2( LPVOID lpParam )
{
for (int i=0; i<5; i++)
{
cout << "func2" << endl;
Sleep(850);
}
ThreadsMarker* tm = reinterpret_cast<ThreadsMarker*>(lpParam);
tm->finishedThreads[2] = true;
cout << "func2 finished" << endl;
return 0;
}
DWORD WINAPI func3( LPVOID lpParam )
{
for (int i=0; i<5; i++)
{
cout << "func3" << endl;
Sleep(670);
}
ThreadsMarker* tm = reinterpret_cast<ThreadsMarker*>(lpParam);
tm->finishedThreads[3] = true;
cout << "func3 finished" << endl;
return 0;
}
int main(int argc, char* argv[])
{
HANDLE handles[NB_THREADS];
DWORD dwThreadId[NB_THREADS];
DWORD dwEvent;
ThreadsMarker tm;
handles[0] = CreateThread( NULL, 0, func0, &tm, 0, &dwThreadId[0]);
handles[1] = CreateThread( NULL, 0, func1, &tm, 0, &dwThreadId[1]);
handles[2] = CreateThread( NULL, 0, func2, &tm, 0, &dwThreadId[2]);
handles[3] = CreateThread( NULL, 0, func3, &tm, 0, &dwThreadId[3]);
dwEvent = WaitForMultipleObjects(NB_THREADS, handles, FALSE, INFINITE);
cout << dwEvent << endl;
cin.get();
return 0;
} |
Partager