因为在需要大量创建线程和销毁线程的时候一个一个创建销毁太麻烦,线程池把不用的线程挂起,做到线程的复用。并且当任务到达时因为省去了创建时间,所以可以快速响应。并且线程池对线程进行统一管理。
1、线程池异步方式调用函数两种方法:
1、不创建工作项的方式
2、创建工作项的方式
#include <iostream>
#include <Windows.h>
#include <vector>
using namespace std;
VOID CALLBACK SimpleCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context);
VOID CALLBACK WorkCallback(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work);
int main()
{
PTP_WORK tpWork;
for (int i = 0; i < 10; ++i)
{
TrySubmitThreadpoolCallback(SimpleCallBack, NULL, NULL); //不创建工作项的方式
}
{//创建工作项的方式
tpWork = CreateThreadpoolWork(WorkCallback, NULL, NULL);
for (int i = 0; i < 10; ++i)
{
SubmitThreadpoolWork(tpWork);
}
WaitForThreadpoolWorkCallbacks(tpWork, false);
CloseThreadpoolWork(tpWork);
}
return 0;
}
VOID CALLBACK SimpleCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context)
{
printf("this is a simple work function ,thread is : %d\n", GetCurrentThreadId());
Sleep(100);
}
VOID CALLBACK WorkCallback(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
printf("this is WorkCallback function,thread id is : %d\n", GetCurrentThreadId());
Sleep(100);
}
结果是:
从结果可以看出,线程确实进行了复用。
2、每隔一段时间调用一次线程函数
#include <iostream>
#include <Windows.h>
#include <vector>
using namespace std;
VOID CALLBACK TimerCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer);
int main()
{
{
PTP_TIMER pt = CreateThreadpoolTimer(TimerCallBack, NULL, NULL);
ULARGE_INTEGER ulRelativeStartTime;
ulRelativeStartTime.QuadPart = (LONGLONG)-(10000000);
FILETIME ftRelativeStartTime;
ftRelativeStartTime.dwHighDateTime = ulRelativeStartTime.HighPart;
ftRelativeStartTime.dwLowDateTime = ulRelativeStartTime.LowPart;
SetThreadpoolTimer(pt, &ftRelativeStartTime, 2000, 0);
/*第二个参数是FILETIME,如果是正数或零,则表示自1601年1月1日(UTC)起的绝对时间,
以100纳秒为单位。如果为负,,则指示相对于当前时间的等待时间。第三个参数是间隔时间,以毫秒为单位*/
if (IsThreadpoolTimerSet(pt))
{
printf("ok\n");
}
Sleep(10000);
WaitForThreadpoolTimerCallbacks(pt, TRUE);
CloseThreadpoolTimer(pt);
}
return 0;
}
VOID CALLBACK TimerCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer)
{
printf("this is a timer work function ,thread is : %d\n", GetCurrentThreadId());
}
3、内核对象触发时调用一个函数
#include <iostream>
#include <Windows.h>
#include <vector>
using namespace std;
VOID CALLBACK WaitCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WAIT Wait, TP_WAIT_RESULT WaitResult);
int main()
{
{
PTP_WAIT pw = CreateThreadpoolWait(WaitCallBack, NULL, NULL);
HANDLE h = CreateEvent(NULL, TRUE, FALSE, NULL); //创建事件
SetThreadpoolWait(pw, h, NULL); //关联内核对象
Sleep(100);
SetEvent(h); //触发事件
Sleep(100);
WaitForThreadpoolWaitCallbacks(pw, TRUE);
CloseThreadpoolWait(pw);
CloseHandle(h);
}
return 0;
}
VOID CALLBACK WaitCallBack(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WAIT Wait, TP_WAIT_RESULT WaitResult)
{
printf("this is a wait work function ,thread is : %d\n", GetCurrentThreadId());
}
4、异步IO完成时调用函数
略