c++ - 将定时器与 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;
}
为什么它不止一次调用回调函数?
解决方案
打电话WaitForThreadpoolWorkCallbacks()
是错误的做法。它等待排队的工作项目CreateThreadpoolWork()
完成,但您没有排队任何工作项目,因此WaitForThreadpoolWorkCallbacks()
立即返回并且您的程序只是退出。
既然无事可做,不如直接调用Sleep()
主线程。或者,您可以让主线程使用 创建一个事件对象CreateEvent()
,然后在计时器回调中发出该事件的信号,并让主线程等待该事件发出信号。
推荐阅读
- javascript - 如何将 JavaScript 中的数据缓冲区转换为文件?
- math - 从 Lua 中的表中选择 N 个均匀分布的元素
- svelte - 在 fetch Sapper 上区分服务器端和客户端
- xml - XSLT 将项目与类匹配
- c++ - 模式生成器
- aws-lambda - 如何使用 Amazon Lex 捕获用户的随机字符串输入
- android - 使用 url_launcher 进行颤振列表搜索
- django - Django 错误:“方法”对象不可下标
- typescript - 为什么 typescript generic T any 不起作用?
- javascript - 我怎样才能让我的线条随着地球旋转?