-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathRBTreeTimer.h
61 lines (48 loc) · 1.25 KB
/
RBTreeTimer.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
// Copyright © 2022 ichenq@gmail.com All rights reserved.
// See accompanying files LICENSE
#pragma once
#include "TimerBase.h"
#include <map>
#include <unordered_map>
// timer scheduler implemented by red-black tree.
// complexity:
// StartTimer CancelTimer PerTick
// O(logN) O(logN) O(logN)
//
class RBTreeTimer : public TimerBase
{
public:
struct NodeKey
{
int id = 0;
int64_t deadline = 0;
bool operator < (const NodeKey& b) const
{
if (deadline == b.deadline) {
return id > b.id;
}
return deadline < b.deadline;
}
};
public:
RBTreeTimer();
~RBTreeTimer();
TimerSchedType Type() const override
{
return TimerSchedType::TIMER_RBTREE;
}
// 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)timers_.size();
}
private:
void clear();
// rbtree map implementation
std::multimap<NodeKey, TimeoutAction> timers_;
std::unordered_map<int , NodeKey> ref_;
};