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