-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathHashedWheelTimer.h
64 lines (49 loc) · 1.5 KB
/
HashedWheelTimer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright © 2021 ichenq@gmail.com All rights reserved.
// See accompanying files LICENSE
#pragma once
#include "TimerBase.h"
#include <vector>
#include <unordered_map>
class HashedWheelBucket;
class HashedWheelTimeout;
// A simple hashed wheel timer inspired by [Netty HashedWheelTimer]
// see https://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/HashedWheelTimer.java
//
// timer scheduler implemented by hashed wheel
// complexity:
// StartTimer CancelTimer PerTick
// O(1) O(1) O(1)
//
class HashedWheelTimer : public TimerBase
{
public:
HashedWheelTimer();
~HashedWheelTimer();
TimerSchedType Type() const override
{
return TimerSchedType::TIMER_HASHED_WHEEL;
}
// start a timer after `duration` milliseconds
int Start(uint32_t duration, TimeoutAction action) override;
// cancel a timer
bool Cancel(int timer_id) override;
int Update(int64_t now = 0) override;
int Size() const override
{
return (int)ref_.size();
}
private:
friend class HashedWheelTimeout;
friend class HashedWheelBucket;
int tick();
void purge();
void delTimeout(HashedWheelTimeout*);
HashedWheelTimeout* allocTimeout(int id, int64_t deadline, TimeoutAction action);
void freeTimeout(HashedWheelTimeout*);
private:
std::vector<HashedWheelBucket*> wheel_;
std::unordered_map<int, HashedWheelTimeout*> ref_;
int ticks_ = 0;
int64_t started_at_ = 0;
int64_t last_time_ = 0;
};