-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtimer_service.cpp
More file actions
126 lines (111 loc) · 2.4 KB
/
timer_service.cpp
File metadata and controls
126 lines (111 loc) · 2.4 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//
// Copyright (c) 2026 Michael Vandeberg
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/cppalliance/capy
//
#include <boost/capy/ex/detail/timer_service.hpp>
namespace boost {
namespace capy {
namespace detail {
timer_service::
timer_service(execution_context& ctx)
: thread_([this] { run(); })
{
(void)ctx;
}
timer_service::
~timer_service()
{
stop_and_join();
}
void
timer_service::
schedule_at(
std::chrono::steady_clock::time_point deadline,
std::function<void()> cb,
timer_id& out)
{
std::lock_guard lock(mutex_);
auto id = ++next_id_;
out = id;
active_ids_.insert(id);
queue_.push(entry{deadline, id, std::move(cb)});
cv_.notify_one();
}
void
timer_service::
cancel(timer_id id)
{
std::unique_lock lock(mutex_);
if(!active_ids_.contains(id))
return;
if(executing_id_ == id)
{
// Callback is running — wait for it to finish.
// run() erases from active_ids_ after execution.
while(executing_id_ == id)
cancel_cv_.wait(lock);
return;
}
active_ids_.erase(id);
}
void
timer_service::
stop_and_join()
{
{
std::lock_guard lock(mutex_);
stopped_ = true;
}
cv_.notify_one();
if(thread_.joinable())
thread_.join();
}
void
timer_service::
shutdown()
{
stop_and_join();
}
void
timer_service::
run()
{
std::unique_lock lock(mutex_);
for(;;)
{
if(stopped_)
return;
if(queue_.empty())
{
cv_.wait(lock);
continue;
}
auto deadline = queue_.top().deadline;
auto now = std::chrono::steady_clock::now();
if(deadline > now)
{
cv_.wait_until(lock, deadline);
continue;
}
// Pop the entry (const_cast needed because priority_queue::top is const)
auto e = std::move(const_cast<entry&>(queue_.top()));
queue_.pop();
// Skip if cancelled (no longer in active set)
if(!active_ids_.contains(e.id))
continue;
executing_id_ = e.id;
lock.unlock();
e.callback();
lock.lock();
active_ids_.erase(e.id);
executing_id_ = 0;
cancel_cv_.notify_all();
}
}
} // detail
} // capy
} // boost