blob: 15b31aa71771c62390fd93e558daed2c4c28f180 [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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <list>
15#include <memory>
16#include <queue>
tommic06b1332016-05-14 11:31:40 -070017
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#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)
30#include "webrtc/base/refcountedobject.h"
31#include "webrtc/base/scoped_ref_ptr.h"
32
33struct 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.
162class LOCKABLE TaskQueue {
163 public:
164 // TaskQueue priority levels. On some platforms these will map to thread
165 // priorities, on others such as Mac and iOS, GCD queue priorities.
166 enum class Priority {
167 NORMAL = 0,
168 HIGH,
169 LOW,
170 };
171
172 explicit TaskQueue(const char* queue_name,
173 Priority priority = Priority::NORMAL);
174 ~TaskQueue();
175
176 static TaskQueue* Current();
177
178 // Used for DCHECKing the current queue.
179 static bool IsCurrent(const char* queue_name);
180 bool IsCurrent() const;
181
182 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
183
184 // Ownership of the task is passed to PostTask.
185 void PostTask(std::unique_ptr<QueuedTask> task);
186 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
187 std::unique_ptr<QueuedTask> reply,
188 TaskQueue* reply_queue);
189 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
190 std::unique_ptr<QueuedTask> reply);
191
192 // Schedules a task to execute a specified number of milliseconds from when
193 // the call is made. The precision should be considered as "best effort"
194 // and in some cases, such as on Windows when all high precision timers have
195 // been used up, can be off by as much as 15 millseconds (although 8 would be
196 // more likely). This can be mitigated by limiting the use of delayed tasks.
197 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
198
199 template <class Closure>
200 void PostTask(const Closure& closure) {
201 PostTask(std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)));
202 }
203
204 // See documentation above for performance expectations.
205 template <class Closure>
206 void PostDelayedTask(const Closure& closure, uint32_t milliseconds) {
207 PostDelayedTask(
208 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)),
209 milliseconds);
210 }
211
212 template <class Closure1, class Closure2>
213 void PostTaskAndReply(const Closure1& task,
214 const Closure2& reply,
215 TaskQueue* reply_queue) {
216 PostTaskAndReply(
217 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
218 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)),
219 reply_queue);
220 }
221
222 template <class Closure>
223 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
224 const Closure& reply) {
225 PostTaskAndReply(std::move(task), std::unique_ptr<QueuedTask>(
226 new ClosureTask<Closure>(reply)));
227 }
228
229 template <class Closure>
230 void PostTaskAndReply(const Closure& task,
231 std::unique_ptr<QueuedTask> reply) {
232 PostTaskAndReply(
233 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(task)),
234 std::move(reply));
235 }
236
237 template <class Closure1, class Closure2>
238 void PostTaskAndReply(const Closure1& task, const Closure2& reply) {
239 PostTaskAndReply(
240 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
241 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)));
242 }
243
244 private:
245#if defined(WEBRTC_BUILD_LIBEVENT)
246 static void ThreadMain(void* context);
247 static void OnWakeup(int socket, short flags, void* context); // NOLINT
248 static void RunTask(int fd, short flags, void* context); // NOLINT
249 static void RunTimer(int fd, short flags, void* context); // NOLINT
250
251 class ReplyTaskOwner;
252 class PostAndReplyTask;
253 class SetTimerTask;
254
255 typedef RefCountedObject<ReplyTaskOwner> ReplyTaskOwnerRef;
256
257 void PrepareReplyTask(scoped_refptr<ReplyTaskOwnerRef> reply_task);
258
259 struct QueueContext;
260
261 int wakeup_pipe_in_ = -1;
262 int wakeup_pipe_out_ = -1;
263 event_base* event_base_;
264 std::unique_ptr<event> wakeup_event_;
265 PlatformThread thread_;
266 rtc::CriticalSection pending_lock_;
267 std::list<std::unique_ptr<QueuedTask>> pending_ GUARDED_BY(pending_lock_);
268 std::list<scoped_refptr<ReplyTaskOwnerRef>> pending_replies_
269 GUARDED_BY(pending_lock_);
270#elif defined(WEBRTC_MAC)
271 struct QueueContext;
272 struct TaskContext;
273 struct PostTaskAndReplyContext;
274 dispatch_queue_t queue_;
275 QueueContext* const context_;
276#elif defined(WEBRTC_WIN)
277 class ThreadState;
278 void RunPendingTasks();
279 static void ThreadMain(void* context);
280
281 class WorkerThread : public PlatformThread {
282 public:
283 WorkerThread(ThreadRunFunction func,
284 void* obj,
285 const char* thread_name,
286 ThreadPriority priority)
287 : PlatformThread(func, obj, thread_name, priority) {}
288
289 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
290 return PlatformThread::QueueAPC(apc_function, data);
291 }
292 };
293 WorkerThread thread_;
294 rtc::CriticalSection pending_lock_;
295 std::queue<std::unique_ptr<QueuedTask>> pending_ GUARDED_BY(pending_lock_);
296 HANDLE in_queue_;
297#else
298#error not supported.
299#endif
300
301 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
302};
303
304} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700305
306#endif // WEBRTC_BASE_TASK_QUEUE_H_