forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CxxMessageQueue.cpp
313 lines (257 loc) · 7.49 KB
/
CxxMessageQueue.cpp
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright 2004-present Facebook. All Rights Reserved.
#include "CxxMessageQueue.h"
#include <folly/AtomicIntrusiveLinkedList.h>
#include <unordered_map>
#include <mutex>
#include <queue>
#include <glog/logging.h>
namespace facebook {
namespace react {
using detail::BinarySemaphore;
using detail::EventFlag;
using clock = std::chrono::steady_clock;
using time_point = clock::time_point;
static_assert(std::is_same<time_point, EventFlag::time_point>::value, "");
namespace {
time_point now() {
return clock::now();
}
class Task {
public:
static Task* create(std::function<void()>&& func) {
return new Task{std::move(func), false, time_point()};
}
static Task* createSync(std::function<void()>&& func) {
return new Task{std::move(func), true, time_point()};
}
static Task* createDelayed(std::function<void()>&& func, time_point startTime) {
return new Task{std::move(func), false, startTime};
}
std::function<void()> func;
// This flag is just to mark that the task is expected to be synchronous. If
// a synchronous task races with stopping the queue, the thread waiting on
// the synchronous task might never resume. We use this flag to detect this
// case and throw an error.
bool sync;
time_point startTime;
folly::AtomicIntrusiveLinkedListHook<Task> hook;
// Should this sort consider id also?
struct Compare {
bool operator()(const Task* a, const Task* b) {
return a->startTime > b->startTime;
}
};
};
class DelayedTaskQueue {
public:
~DelayedTaskQueue() {
while (!queue_.empty()) {
delete queue_.top();
queue_.pop();
}
}
void process() {
while (!queue_.empty()) {
Task* d = queue_.top();
if (now() < d->startTime) {
break;
}
auto owned = std::unique_ptr<Task>(queue_.top());
queue_.pop();
owned->func();
}
}
void push(Task* t) {
queue_.push(t);
}
bool empty() {
return queue_.empty();
}
time_point nextTime() {
return queue_.top()->startTime;
}
private:
std::priority_queue<Task*, std::vector<Task*>, Task::Compare> queue_;
};
}
class CxxMessageQueue::QueueRunner {
public:
~QueueRunner() {
queue_.sweep([] (Task* t) {
delete t;
});
}
void enqueue(std::function<void()>&& func) {
enqueueTask(Task::create(std::move(func)));
}
void enqueueDelayed(std::function<void()>&& func, uint64_t delayMs) {
if (delayMs) {
enqueueTask(Task::createDelayed(std::move(func), now() + std::chrono::milliseconds(delayMs)));
} else {
enqueue(std::move(func));
}
}
void enqueueSync(std::function<void()>&& func) {
EventFlag done;
enqueueTask(Task::createSync([&] () mutable {
func();
done.set();
}));
if (stopped_) {
// If this queue is stopped_, the sync task might never actually run.
throw std::runtime_error("Stopped within enqueueSync.");
}
done.wait();
}
void stop() {
stopped_ = true;
pending_.set();
}
bool isStopped() {
return stopped_;
}
void quitSynchronous() {
stop();
finished_.wait();
}
void run() {
// If another thread stops this one, then the acquire-release on pending_
// ensures that we read stopped some time after it was set (and other
// threads just have to deal with the fact that we might run a task "after"
// they stop us).
//
// If we are stopped on this thread, then memory order doesn't really
// matter reading stopped_.
while (!stopped_.load(std::memory_order_relaxed)) {
sweep();
if (delayed_.empty()) {
pending_.wait();
} else {
pending_.wait_until(delayed_.nextTime());
}
}
// This sweep is just to catch erroneous enqueueSync. That is, there could
// be a task marked sync that another thread is waiting for, but we'll
// never actually run it.
sweep();
finished_.set();
}
// We are processing two queues, the posted tasks (queue_) and the delayed
// tasks (delayed_). Delayed tasks first go into posted tasks, and then are
// moved to the delayed queue if we pop them before the time they are
// scheduled for.
// As we pop things from queue_, before dealing with that thing, we run any
// delayed tasks whose scheduled time has arrived.
void sweep() {
queue_.sweep([this] (Task* t) {
std::unique_ptr<Task> owned(t);
if (stopped_.load(std::memory_order_relaxed)) {
if (t->sync) {
throw std::runtime_error("Sync task posted while stopped.");
}
return;
}
delayed_.process();
if (t->startTime != time_point() && now() <= t->startTime) {
delayed_.push(owned.release());
} else {
t->func();
}
});
delayed_.process();
}
void bindToThisThread() {
if (tid_ != std::thread::id{}) {
throw std::runtime_error("Message queue already bound to thread.");
}
tid_ = std::this_thread::get_id();
}
bool isOnQueue() {
return std::this_thread::get_id() == tid_;
}
private:
void enqueueTask(Task* task) {
if (queue_.insertHead(task)) {
pending_.set();
}
}
std::thread::id tid_;
folly::AtomicIntrusiveLinkedList<Task, &Task::hook> queue_;
std::atomic_bool stopped_{false};
DelayedTaskQueue delayed_;
BinarySemaphore pending_;
EventFlag finished_;
};
CxxMessageQueue::CxxMessageQueue() : qr_(new QueueRunner()) {
}
CxxMessageQueue::~CxxMessageQueue() {
// TODO(cjhopman): Add detach() so that the queue doesn't have to be
// explicitly stopped.
if (!qr_->isStopped()) {
LOG(FATAL) << "Queue not stopped.";
}
}
void CxxMessageQueue::runOnQueue(std::function<void()>&& func) {
qr_->enqueue(std::move(func));
}
void CxxMessageQueue::runOnQueueDelayed(std::function<void()>&& func, uint64_t delayMs) {
qr_->enqueueDelayed(std::move(func), delayMs);
}
void CxxMessageQueue::runOnQueueSync(std::function<void()>&& func) {
if (isOnQueue()) {
func();
return;
}
qr_->enqueueSync(std::move(func));
}
void CxxMessageQueue::quitSynchronous() {
if (isOnQueue()) {
qr_->stop();
} else {
qr_->quitSynchronous();
}
}
bool CxxMessageQueue::isOnQueue() {
return qr_->isOnQueue();
}
namespace {
struct MQRegistry {
std::weak_ptr<CxxMessageQueue> find(std::thread::id tid) {
std::lock_guard<std::mutex> g(lock_);
auto iter = registry_.find(tid);
if (iter == registry_.end()) return std::weak_ptr<CxxMessageQueue>();
return iter->second;
}
void registerQueue(std::thread::id tid, std::weak_ptr<CxxMessageQueue> mq) {
std::lock_guard<std::mutex> g(lock_);
registry_[tid] = mq;
}
void unregister(std::thread::id tid) {
std::lock_guard<std::mutex> g(lock_);
registry_.erase(tid);
}
private:
std::mutex lock_;
std::unordered_map<std::thread::id, std::weak_ptr<CxxMessageQueue>> registry_;
};
MQRegistry& getMQRegistry() {
static MQRegistry* mq_registry = new MQRegistry();
return *mq_registry;
}
}
std::weak_ptr<CxxMessageQueue> CxxMessageQueue::current() {
auto tid = std::this_thread::get_id();
return getMQRegistry().find(tid);
}
std::function<void()> CxxMessageQueue::getRunLoop(std::shared_ptr<CxxMessageQueue> mq) {
return [capture=mq->qr_, weakMq=std::weak_ptr<CxxMessageQueue>(mq)] {
capture->bindToThisThread();
auto tid = std::this_thread::get_id();
// TODO: handle nested runloops (either allow them or throw an exception).
getMQRegistry().registerQueue(tid, weakMq);
capture->run();
getMQRegistry().unregister(tid);
};
}
} // namespace react
} // namespace facebook