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
|
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <process.h>
#include <stdio.h>
struct ThreadInfo
{
ThreadInfo();
~ThreadInfo();
HANDLE fire;
HANDLE stop;
private:
ThreadInfo(const ThreadInfo &);
ThreadInfo& operator=(const ThreadInfo &);
};
ThreadInfo::ThreadInfo()
{
fire = CreateEvent(0, FALSE, FALSE, NULL);
stop = CreateEvent(0, TRUE, FALSE, NULL);
}
ThreadInfo::~ThreadInfo()
{
CloseHandle(stop);
CloseHandle(fire);
}
unsigned __stdcall threadfunc(void* param)
{
if (ThreadInfo* info = reinterpret_cast<ThreadInfo*>(param))
{
char buf[32];
for (;;)
{
HANDLE h[2] = { info->fire, info->stop };
DWORD ret = WaitForMultipleObjects(2, h, FALSE, INFINITE);
if (ret == WAIT_OBJECT_0)
{
_snprintf(buf, sizeof(buf), "Thread %ld fired\n", GetCurrentThreadId());
printf(buf);
}
else if (ret == WAIT_OBJECT_0+1)
{
_snprintf(buf, sizeof(buf), "Thread %ld clean shutdown\n", GetCurrentThreadId());
printf(buf);
break;
}
else
{
_snprintf(buf, sizeof(buf), "Thread %ld abnormal shutdown\n", GetCurrentThreadId());
printf(buf);
break;
}
}
}
return 0;
}
int main()
{
const size_t N = 5;
ThreadInfo info[N];
HANDLE h[N];
for (size_t i = 0; i != N; ++i)
{
unsigned threadid;
h[i] = (HANDLE)_beginthreadex(0, 0, threadfunc, &info[i], 0, &threadid);
}
Sleep(5*1000);
for (size_t i = 0; i != N; ++i)
SetEvent(info[i].fire);
Sleep(5*1000);
for (size_t i = 0; i != N; ++i)
SetEvent(info[i].stop);
Sleep(5*1000);
return 0;
}
|