// ThreadPool.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
using namespace std;
PTP_TIMER g_Timer;
PTP_WORK work1, work2; //2个线程。
void A();
void B();
void C();
void D();
volatile LONG iCount = 0;
HANDLE hEvent = NULL; // FINISH
HANDLE ha, hb, hc, hd;
CRITICAL_SECTION g_cs;
VOID NTAPI thread_x(PTP_CALLBACK_INSTANCE, PVOID, PTP_WORK)
{
A();
C();
}
VOID NTAPI thread_y(PTP_CALLBACK_INSTANCE, PVOID, PTP_WORK)
{
B();
D();
}
VOID NTAPI TimerHandler(PTP_CALLBACK_INSTANCE, PVOID, PTP_TIMER)
{
//InterlockedIncrement(&iCount);
if (iCount < 10)
{
SetEvent(hd);
}
}
void A()
{
WaitForSingleObject(ha, INFINITE);
ResetEvent(ha);
EnterCriticalSection(&g_cs);
cout << "命令A\n";
LeaveCriticalSection(&g_cs);
SetEvent(hb);
}
void C()
{
WaitForSingleObject(hc, INFINITE);
ResetEvent(hc);
EnterCriticalSection(&g_cs);
cout << "命令C\n";
LeaveCriticalSection(&g_cs);
FILETIME ft;
ULARGE_INTEGER ulRelativeTime;
ulRelativeTime.QuadPart = (LONGLONG)-3*10000000;
ft.dwHighDateTime = ulRelativeTime.HighPart;
ft.dwLowDateTime = ulRelativeTime.LowPart;
SetThreadpoolTimer(g_Timer, &ft, 0, 0); //由这个来发信号
}
void B()
{
WaitForSingleObject(hb, INFINITE);
ResetEvent(hb);
EnterCriticalSection(&g_cs);
cout << "命令B\n";
LeaveCriticalSection(&g_cs);
SetEvent(hc);
}
void D()
{
WaitForSingleObject(hd, INFINITE);
ResetEvent(hd);
EnterCriticalSection(&g_cs);
cout << "命令D\n";
cout << "第" << iCount << "计算\n";
LeaveCriticalSection(&g_cs);
if (++iCount < 10)
{
SubmitThreadpoolWork(work1);
SubmitThreadpoolWork(work2);
SetEvent(ha);
}
else
{
SetEvent(hEvent);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&g_cs);
ha = CreateEvent(NULL, TRUE, FALSE, NULL);
hb = CreateEvent(NULL, TRUE, FALSE, NULL);
hc = CreateEvent(NULL, TRUE, FALSE, NULL);
hd = CreateEvent(NULL, TRUE, FALSE, NULL);
work1 = CreateThreadpoolWork(thread_x, NULL, NULL);
work2 = CreateThreadpoolWork(thread_y, NULL, NULL);
g_Timer = CreateThreadpoolTimer(&TimerHandler, 0, 0);
hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
SubmitThreadpoolWork(work1);
SubmitThreadpoolWork(work2);
SetEvent(ha);
WaitForSingleObject(hEvent, INFINITE);
DeleteCriticalSection(&g_cs);
cout << "finished.\n";
return 0;
}