Windows 上原生Timer常用的有下面两个:
1. SetTimer windows上最简单方便的定时器,不足之处是要依赖消息循环,不能在工作线程使用。时钟到了会将WM_TIMER放入消息队列,也会收到消息队列中消息数量和消息处理过程影响
2. SetWaitableTimer 内核定时器,可以在任何线程使用。精度也较SetTimer高,不过对不同系统这个默认精度不同,可以通过timeBeginPeriod设置,这个在msdn SetWaitableTimer 的介绍中也有提到:SetWaitableTimer function (synchapi.h) - Win32 apps | Microsoft DocsActivates the specified waitable timer. When the due time arrives, the timer is signaled and the thread that set the timer calls the optional completion routine.
https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setwaitabletimer
APIs that deal with timers use various different hardware clocks. These clocks may have resolutions significantly different from what you expect: some may be measured in milliseconds (for those that use an RTC-based timer chip), to those measured in nanoseconds (for those that use ACPI or TSC counters). You can change the resolution of your API with a call to the timeBeginPeriod and timeEndPeriod functions. How precise you can change the resolution depends on which hardware clock the particular API uses. For more information, check your hardware documentation.
通过超时机制自定义timer:
上面是 windows 原生定时器,也可以通过超时机制自己构建一个定时器,比如windows 上可以利用Sleep/WaitForSingleObject等支持超时的函数,配合循环完成一个自制的定时器。
跨平台的方案也有,比如boost::asio中就有定时器支持。也可以利用std::this_thread::sleep_for \ std::condition_variable的wait_for超时,socket的select超时,来实现自定义定时器。

本文介绍了Windows上两种原生定时器:SetTimer和SetWaitableTimer,分析了它们的使用场景和精度差异,并讨论了通过超时机制自定义定时器的方法,包括使用Sleep/WaitForSingleObject以及跨平台方案如boost::asio和C++标准库中的工具。
950

被折叠的 条评论
为什么被折叠?



