首页 > 解决方案 > 将定时器与 Windows 线程池一起使用

问题描述

我编写了以下程序,它应该第 10 次打印一些东西。我想使用计时器和线程池来实现以下程序,但该程序只显示一条消息,然后程序将退出。

#include <windows.h>
#include <process.h>
#include <iostream>


// How many seconds we'll display the message box
int g_nSecLeft = 10;

PTP_WORK g_WorkItem = NULL;

VOID CALLBACK WorkerOne(PTP_CALLBACK_INSTANCE arg_instance, PVOID arg_context, PTP_TIMER arg_timer)
{
    std::printf("You have %d seconds to respond", --g_nSecLeft);
}

int main(int argc, char* argv[])
{
    // Create the thread pool timer object
    PTP_TIMER pointer_timer = CreateThreadpoolTimer(WorkerOne, NULL, NULL);

    if (pointer_timer == NULL) 
    {
        std::cout << "Error: something goes wrong." << std::endl;
        return -1;
    }

    // Start the timer in one second to trigger every 1 second
    ULARGE_INTEGER relative_start_time;
    relative_start_time.QuadPart = (LONGLONG)-(10000000); // start in 1 second
    
    FILETIME ft_relative_start_time;
    ft_relative_start_time.dwHighDateTime = relative_start_time.HighPart;
    ft_relative_start_time.dwLowDateTime = relative_start_time.LowPart;
    
    SetThreadpoolTimer(pointer_timer, &ft_relative_start_time, 1000, 0);
    
    if (IsThreadpoolTimerSet(pointer_timer))
    {
        std::cout << "Time has been set." << std::endl;
    }

    WaitForThreadpoolWorkCallbacks(g_WorkItem, FALSE);
    
    return 0;
}

为什么它不止一次调用回调函数?

标签: c++winapi

解决方案


打电话WaitForThreadpoolWorkCallbacks()是错误的做法。它等待排队的工作项目CreateThreadpoolWork()完成,但您没有排队任何工作项目,因此WaitForThreadpoolWorkCallbacks()立即返回并且您的程序只是退出。

既然无事可做,不如直接调用Sleep()主线程。或者,您可以让主线程使用 创建一个事件对象CreateEvent(),然后在计时器回调中发出该事件的信号,并让主线程等待该事件发出信号。


推荐阅读