blob: 92a1c9477a090cacc7fb4652ccc578a47f3cc359 [file] [log] [blame]
tommic06b1332016-05-14 11:31:40 -07001/*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_BASE_TASK_QUEUE_H_
12#define WEBRTC_BASE_TASK_QUEUE_H_
13
14#include <list>
15#include <memory>
tommib89257a2016-07-12 01:24:36 -070016#include <unordered_map>
tommic06b1332016-05-14 11:31:40 -070017
18#if defined(WEBRTC_MAC) && !defined(WEBRTC_BUILD_LIBEVENT)
19#include <dispatch/dispatch.h>
20#endif
21
22#include "webrtc/base/constructormagic.h"
23#include "webrtc/base/criticalsection.h"
24
25#if defined(WEBRTC_WIN) || defined(WEBRTC_BUILD_LIBEVENT)
26#include "webrtc/base/platform_thread.h"
27#endif
28
29#if defined(WEBRTC_BUILD_LIBEVENT)
tommi8c80c6e2017-02-23 00:34:52 -080030#include "webrtc/base/refcountedobject.h"
31#include "webrtc/base/scoped_ref_ptr.h"
32
tommic06b1332016-05-14 11:31:40 -070033struct event_base;
34struct event;
35#endif
36
37namespace rtc {
38
39// Base interface for asynchronously executed tasks.
40// The interface basically consists of a single function, Run(), that executes
41// on the target queue. For more details see the Run() method and TaskQueue.
42class QueuedTask {
43 public:
44 QueuedTask() {}
45 virtual ~QueuedTask() {}
46
47 // Main routine that will run when the task is executed on the desired queue.
48 // The task should return |true| to indicate that it should be deleted or
49 // |false| to indicate that the queue should consider ownership of the task
50 // having been transferred. Returning |false| can be useful if a task has
51 // re-posted itself to a different queue or is otherwise being re-used.
52 virtual bool Run() = 0;
53
54 private:
55 RTC_DISALLOW_COPY_AND_ASSIGN(QueuedTask);
56};
57
58// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
59template <class Closure>
60class ClosureTask : public QueuedTask {
61 public:
62 explicit ClosureTask(const Closure& closure) : closure_(closure) {}
63
64 private:
65 bool Run() override {
66 closure_();
67 return true;
68 }
69
70 Closure closure_;
71};
72
73// Extends ClosureTask to also allow specifying cleanup code.
74// This is useful when using lambdas if guaranteeing cleanup, even if a task
75// was dropped (queue is too full), is required.
76template <class Closure, class Cleanup>
77class ClosureTaskWithCleanup : public ClosureTask<Closure> {
78 public:
79 ClosureTaskWithCleanup(const Closure& closure, Cleanup cleanup)
80 : ClosureTask<Closure>(closure), cleanup_(cleanup) {}
81 ~ClosureTaskWithCleanup() { cleanup_(); }
82
83 private:
84 Cleanup cleanup_;
85};
86
87// Convenience function to construct closures that can be passed directly
88// to methods that support std::unique_ptr<QueuedTask> but not template
89// based parameters.
90template <class Closure>
91static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure) {
92 return std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure));
93}
94
95template <class Closure, class Cleanup>
96static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure,
97 const Cleanup& cleanup) {
98 return std::unique_ptr<QueuedTask>(
99 new ClosureTaskWithCleanup<Closure, Cleanup>(closure, cleanup));
100}
101
102// Implements a task queue that asynchronously executes tasks in a way that
103// guarantees that they're executed in FIFO order and that tasks never overlap.
104// Tasks may always execute on the same worker thread and they may not.
105// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
106//
107// Here are some usage examples:
108//
109// 1) Asynchronously running a lambda:
110//
111// class MyClass {
112// ...
113// TaskQueue queue_("MyQueue");
114// };
115//
116// void MyClass::StartWork() {
117// queue_.PostTask([]() { Work(); });
118// ...
119//
120// 2) Doing work asynchronously on a worker queue and providing a notification
121// callback on the current queue, when the work has been done:
122//
123// void MyClass::StartWorkAndLetMeKnowWhenDone(
124// std::unique_ptr<QueuedTask> callback) {
125// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
126// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
127// }
128// ...
129// my_class->StartWorkAndLetMeKnowWhenDone(
130// NewClosure([]() { LOG(INFO) << "The work is done!";}));
131//
132// 3) Posting a custom task on a timer. The task posts itself again after
133// every running:
134//
135// class TimerTask : public QueuedTask {
136// public:
137// TimerTask() {}
138// private:
139// bool Run() override {
140// ++count_;
141// TaskQueue::Current()->PostDelayedTask(
142// std::unique_ptr<QueuedTask>(this), 1000);
143// // Ownership has been transferred to the next occurance,
144// // so return false to prevent from being deleted now.
145// return false;
146// }
147// int count_ = 0;
148// };
149// ...
150// queue_.PostDelayedTask(
151// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
152//
153// For more examples, see task_queue_unittests.cc.
154//
155// A note on destruction:
156//
157// When a TaskQueue is deleted, pending tasks will not be executed but they will
158// be deleted. The deletion of tasks may happen asynchronously after the
159// TaskQueue itself has been deleted or it may happen synchronously while the
160// TaskQueue instance is being deleted. This may vary from one OS to the next
161// so assumptions about lifetimes of pending tasks should not be made.
danilchap8e572f02016-05-19 06:49:03 -0700162class LOCKABLE TaskQueue {
tommic06b1332016-05-14 11:31:40 -0700163 public:
164 explicit TaskQueue(const char* queue_name);
165 // TODO(tommi): Implement move semantics?
166 ~TaskQueue();
167
168 static TaskQueue* Current();
169
170 // Used for DCHECKing the current queue.
171 static bool IsCurrent(const char* queue_name);
172 bool IsCurrent() const;
173
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700174 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
tommic06b1332016-05-14 11:31:40 -0700175
176 // Ownership of the task is passed to PostTask.
177 void PostTask(std::unique_ptr<QueuedTask> task);
178 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
179 std::unique_ptr<QueuedTask> reply,
180 TaskQueue* reply_queue);
181 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
182 std::unique_ptr<QueuedTask> reply);
183
tommif9d91542017-02-17 02:47:11 -0800184 // Schedules a task to execute a specified number of milliseconds from when
185 // the call is made. The precision should be considered as "best effort"
186 // and in some cases, such as on Windows when all high precision timers have
187 // been used up, can be off by as much as 15 millseconds (although 8 would be
188 // more likely). This can be mitigated by limiting the use of delayed tasks.
tommic06b1332016-05-14 11:31:40 -0700189 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
190
191 template <class Closure>
192 void PostTask(const Closure& closure) {
193 PostTask(std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)));
194 }
195
tommif9d91542017-02-17 02:47:11 -0800196 // See documentation above for performance expectations.
tommic06b1332016-05-14 11:31:40 -0700197 template <class Closure>
198 void PostDelayedTask(const Closure& closure, uint32_t milliseconds) {
199 PostDelayedTask(
200 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)),
201 milliseconds);
202 }
203
204 template <class Closure1, class Closure2>
205 void PostTaskAndReply(const Closure1& task,
206 const Closure2& reply,
207 TaskQueue* reply_queue) {
208 PostTaskAndReply(
209 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
210 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)),
211 reply_queue);
212 }
213
214 template <class Closure>
215 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
216 const Closure& reply) {
217 PostTaskAndReply(std::move(task), std::unique_ptr<QueuedTask>(
218 new ClosureTask<Closure>(reply)));
219 }
220
221 template <class Closure>
222 void PostTaskAndReply(const Closure& task,
223 std::unique_ptr<QueuedTask> reply) {
224 PostTaskAndReply(
225 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(task)),
226 std::move(reply));
227 }
228
229 template <class Closure1, class Closure2>
230 void PostTaskAndReply(const Closure1& task, const Closure2& reply) {
231 PostTaskAndReply(
232 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
233 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)));
234 }
235
236 private:
237#if defined(WEBRTC_BUILD_LIBEVENT)
tommi0f8b4032017-02-22 11:22:05 -0800238 static void ThreadMain(void* context);
tommic06b1332016-05-14 11:31:40 -0700239 static void OnWakeup(int socket, short flags, void* context); // NOLINT
240 static void RunTask(int fd, short flags, void* context); // NOLINT
241 static void RunTimer(int fd, short flags, void* context); // NOLINT
242
tommi8c80c6e2017-02-23 00:34:52 -0800243 class ReplyTaskOwner;
tommic06b1332016-05-14 11:31:40 -0700244 class PostAndReplyTask;
245 class SetTimerTask;
246
tommi8c80c6e2017-02-23 00:34:52 -0800247 typedef RefCountedObject<ReplyTaskOwner> ReplyTaskOwnerRef;
248
249 void PrepareReplyTask(scoped_refptr<ReplyTaskOwnerRef> reply_task);
tommic06b1332016-05-14 11:31:40 -0700250
251 struct QueueContext;
252
253 int wakeup_pipe_in_ = -1;
254 int wakeup_pipe_out_ = -1;
255 event_base* event_base_;
256 std::unique_ptr<event> wakeup_event_;
257 PlatformThread thread_;
258 rtc::CriticalSection pending_lock_;
259 std::list<std::unique_ptr<QueuedTask>> pending_ GUARDED_BY(pending_lock_);
tommi8c80c6e2017-02-23 00:34:52 -0800260 std::list<scoped_refptr<ReplyTaskOwnerRef>> pending_replies_
261 GUARDED_BY(pending_lock_);
tommic06b1332016-05-14 11:31:40 -0700262#elif defined(WEBRTC_MAC)
263 struct QueueContext;
264 struct TaskContext;
265 struct PostTaskAndReplyContext;
266 dispatch_queue_t queue_;
267 QueueContext* const context_;
268#elif defined(WEBRTC_WIN)
tommif9d91542017-02-17 02:47:11 -0800269 class MultimediaTimer;
tommib89257a2016-07-12 01:24:36 -0700270 typedef std::unordered_map<UINT_PTR, std::unique_ptr<QueuedTask>>
271 DelayedTasks;
tommi0f8b4032017-02-22 11:22:05 -0800272 static void ThreadMain(void* context);
tommif9d91542017-02-17 02:47:11 -0800273 static bool ProcessQueuedMessages(DelayedTasks* delayed_tasks,
274 std::vector<MultimediaTimer>* timers);
tommic06b1332016-05-14 11:31:40 -0700275
276 class WorkerThread : public PlatformThread {
277 public:
278 WorkerThread(ThreadRunFunction func, void* obj, const char* thread_name)
279 : PlatformThread(func, obj, thread_name) {}
280
281 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
282 return PlatformThread::QueueAPC(apc_function, data);
283 }
284 };
285 WorkerThread thread_;
286#else
287#error not supported.
288#endif
289
290 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
291};
292
293} // namespace rtc
294
295#endif // WEBRTC_BASE_TASK_QUEUE_H_