VLink  2.0.0
A high-performance communication middleware
wheel_timer.h 文件参考

Hashed timing wheel for managing very large pools of concurrent timeouts. 更多...

#include <cstdint>
#include <memory>
#include "./functional.h"
#include "./macros.h"
wheel_timer.h 的引用(Include)关系图:

浏览源代码.

class  vlink::WheelTimer
 O(1) hashed-timing-wheel scheduler backed by an internal worker thread. 更多...
 

命名空间

 

详细描述

Hashed timing wheel for managing very large pools of concurrent timeouts.

vlink::WheelTimer implements the classic hashed-timing-wheel data structure that provides O(1) insertion, O(1) removal and O(k) per-tick expiry processing, where k is the number of timers in the current slot. It scales comfortably to tens or hundreds of thousands of independent timeouts (for example, a session manager or a connection keep-alive supervisor).

Wheel layout for a wheel with S slots advancing every interval_ms milliseconds:

*                        cursor
*                          v
*   +-----+-----+-----+-----+-----+-----+-----+-----+ ... +-----+
*   |  0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  | ... | S-1 |
*   +-----+-----+-----+--+--+-----+-----+--+--+-----+ ... +-----+
*                        |                 |
*               handler list:     handler list:
*                 - {key, round=0, cb}     - {key, round=2, cb}
*                 - {key, round=1, cb}
* 

Timers with timeouts longer than S * interval_ms wrap around using a round counter that is decremented on every cursor pass. Removal is O(1) via a key-to-slot map maintained alongside the wheel.

Lifecycle:

  1. Construct with WheelTimer(slots, interval_ms).
  2. Call start() to launch the worker thread.
  3. Insert timers via add(); keep the returned Key for later removal.
  4. Call stop() to terminate the worker thread.
注解
  • Expiry callbacks run on the wheel's worker thread; marshal results back through a MessageLoop or a lock when shared state is involved.
  • set_catchup_limit() bounds how many missed slots are processed per tick to keep a single iteration from blocking for too long after a system sleep.
Example
vlink::WheelTimer wheel(256, 10);
wheel.start();
auto key = wheel.add(1000, [](vlink::WheelTimer::Key k) {
(void)k;
});
auto repeat_key = wheel.add(500, [](vlink::WheelTimer::Key k) { (void)k; }, 500);
wheel.remove(key);
wheel.stop();