blob: e7eac2f18535ac7030d8c810b11fbf7c1d777800 [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
Henrik Kjellanderc0362762017-06-29 08:03:04 +020011#ifndef WEBRTC_RTC_BASE_TASK_QUEUE_H_
12#define WEBRTC_RTC_BASE_TASK_QUEUE_H_
tommic06b1332016-05-14 11:31:40 -070013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <list>
15#include <memory>
16#include <queue>
tommic06b1332016-05-14 11:31:40 -070017
perkj650fdae2017-08-25 05:00:11 -070018#if defined(WEBRTC_MAC)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020019#include <dispatch/dispatch.h>
20#endif
21
kjellandere96c45b2017-06-30 10:45:21 -070022#include "webrtc/rtc_base/constructormagic.h"
23#include "webrtc/rtc_base/criticalsection.h"
kjellandere96c45b2017-06-30 10:45:21 -070024#include "webrtc/rtc_base/scoped_ref_ptr.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025
perkj650fdae2017-08-25 05:00:11 -070026#if defined(WEBRTC_WIN)
27#include "webrtc/rtc_base/platform_thread.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020028#endif
29
30namespace rtc {
31
32// Base interface for asynchronously executed tasks.
33// The interface basically consists of a single function, Run(), that executes
34// on the target queue. For more details see the Run() method and TaskQueue.
35class QueuedTask {
36 public:
37 QueuedTask() {}
38 virtual ~QueuedTask() {}
39
40 // Main routine that will run when the task is executed on the desired queue.
41 // The task should return |true| to indicate that it should be deleted or
42 // |false| to indicate that the queue should consider ownership of the task
43 // having been transferred. Returning |false| can be useful if a task has
44 // re-posted itself to a different queue or is otherwise being re-used.
45 virtual bool Run() = 0;
46
47 private:
48 RTC_DISALLOW_COPY_AND_ASSIGN(QueuedTask);
49};
50
51// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
52template <class Closure>
53class ClosureTask : public QueuedTask {
54 public:
55 explicit ClosureTask(const Closure& closure) : closure_(closure) {}
56
57 private:
58 bool Run() override {
59 closure_();
60 return true;
61 }
62
63 Closure closure_;
64};
65
66// Extends ClosureTask to also allow specifying cleanup code.
67// This is useful when using lambdas if guaranteeing cleanup, even if a task
68// was dropped (queue is too full), is required.
69template <class Closure, class Cleanup>
70class ClosureTaskWithCleanup : public ClosureTask<Closure> {
71 public:
72 ClosureTaskWithCleanup(const Closure& closure, Cleanup cleanup)
73 : ClosureTask<Closure>(closure), cleanup_(cleanup) {}
74 ~ClosureTaskWithCleanup() { cleanup_(); }
75
76 private:
77 Cleanup cleanup_;
78};
79
80// Convenience function to construct closures that can be passed directly
81// to methods that support std::unique_ptr<QueuedTask> but not template
82// based parameters.
83template <class Closure>
84static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure) {
85 return std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure));
86}
87
88template <class Closure, class Cleanup>
89static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure,
90 const Cleanup& cleanup) {
91 return std::unique_ptr<QueuedTask>(
92 new ClosureTaskWithCleanup<Closure, Cleanup>(closure, cleanup));
93}
94
95// Implements a task queue that asynchronously executes tasks in a way that
96// guarantees that they're executed in FIFO order and that tasks never overlap.
97// Tasks may always execute on the same worker thread and they may not.
98// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
99//
100// Here are some usage examples:
101//
102// 1) Asynchronously running a lambda:
103//
104// class MyClass {
105// ...
106// TaskQueue queue_("MyQueue");
107// };
108//
109// void MyClass::StartWork() {
110// queue_.PostTask([]() { Work(); });
111// ...
112//
113// 2) Doing work asynchronously on a worker queue and providing a notification
114// callback on the current queue, when the work has been done:
115//
116// void MyClass::StartWorkAndLetMeKnowWhenDone(
117// std::unique_ptr<QueuedTask> callback) {
118// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
119// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
120// }
121// ...
122// my_class->StartWorkAndLetMeKnowWhenDone(
123// NewClosure([]() { LOG(INFO) << "The work is done!";}));
124//
125// 3) Posting a custom task on a timer. The task posts itself again after
126// every running:
127//
128// class TimerTask : public QueuedTask {
129// public:
130// TimerTask() {}
131// private:
132// bool Run() override {
133// ++count_;
134// TaskQueue::Current()->PostDelayedTask(
135// std::unique_ptr<QueuedTask>(this), 1000);
136// // Ownership has been transferred to the next occurance,
137// // so return false to prevent from being deleted now.
138// return false;
139// }
140// int count_ = 0;
141// };
142// ...
143// queue_.PostDelayedTask(
144// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
145//
146// For more examples, see task_queue_unittests.cc.
147//
148// A note on destruction:
149//
150// When a TaskQueue is deleted, pending tasks will not be executed but they will
151// be deleted. The deletion of tasks may happen asynchronously after the
152// TaskQueue itself has been deleted or it may happen synchronously while the
153// TaskQueue instance is being deleted. This may vary from one OS to the next
154// so assumptions about lifetimes of pending tasks should not be made.
155class LOCKABLE TaskQueue {
156 public:
157 // TaskQueue priority levels. On some platforms these will map to thread
158 // priorities, on others such as Mac and iOS, GCD queue priorities.
159 enum class Priority {
160 NORMAL = 0,
161 HIGH,
162 LOW,
163 };
164
165 explicit TaskQueue(const char* queue_name,
166 Priority priority = Priority::NORMAL);
167 ~TaskQueue();
168
169 static TaskQueue* Current();
170
171 // Used for DCHECKing the current queue.
172 static bool IsCurrent(const char* queue_name);
173 bool IsCurrent() const;
174
175 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
176
177 // Ownership of the task is passed to PostTask.
178 void PostTask(std::unique_ptr<QueuedTask> task);
179 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
180 std::unique_ptr<QueuedTask> reply,
181 TaskQueue* reply_queue);
182 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
183 std::unique_ptr<QueuedTask> reply);
184
185 // Schedules a task to execute a specified number of milliseconds from when
186 // the call is made. The precision should be considered as "best effort"
187 // and in some cases, such as on Windows when all high precision timers have
188 // been used up, can be off by as much as 15 millseconds (although 8 would be
189 // more likely). This can be mitigated by limiting the use of delayed tasks.
190 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
191
192 template <class Closure>
193 void PostTask(const Closure& closure) {
194 PostTask(std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)));
195 }
196
197 // See documentation above for performance expectations.
198 template <class Closure>
199 void PostDelayedTask(const Closure& closure, uint32_t milliseconds) {
200 PostDelayedTask(
201 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)),
202 milliseconds);
203 }
204
205 template <class Closure1, class Closure2>
206 void PostTaskAndReply(const Closure1& task,
207 const Closure2& reply,
208 TaskQueue* reply_queue) {
209 PostTaskAndReply(
210 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
211 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)),
212 reply_queue);
213 }
214
215 template <class Closure>
216 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
217 const Closure& reply) {
218 PostTaskAndReply(std::move(task), std::unique_ptr<QueuedTask>(
219 new ClosureTask<Closure>(reply)));
220 }
221
222 template <class Closure>
223 void PostTaskAndReply(const Closure& task,
224 std::unique_ptr<QueuedTask> reply) {
225 PostTaskAndReply(
226 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(task)),
227 std::move(reply));
228 }
229
230 template <class Closure1, class Closure2>
231 void PostTaskAndReply(const Closure1& task, const Closure2& reply) {
232 PostTaskAndReply(
233 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
234 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)));
235 }
236
237 private:
perkj650fdae2017-08-25 05:00:11 -0700238#if defined(WEBRTC_MAC)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200239 struct QueueContext;
240 struct TaskContext;
241 struct PostTaskAndReplyContext;
242 dispatch_queue_t queue_;
243 QueueContext* const context_;
244#elif defined(WEBRTC_WIN)
245 class ThreadState;
246 void RunPendingTasks();
247 static void ThreadMain(void* context);
248
249 class WorkerThread : public PlatformThread {
250 public:
251 WorkerThread(ThreadRunFunction func,
252 void* obj,
253 const char* thread_name,
254 ThreadPriority priority)
255 : PlatformThread(func, obj, thread_name, priority) {}
256
257 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
258 return PlatformThread::QueueAPC(apc_function, data);
259 }
260 };
261 WorkerThread thread_;
262 rtc::CriticalSection pending_lock_;
263 std::queue<std::unique_ptr<QueuedTask>> pending_ GUARDED_BY(pending_lock_);
264 HANDLE in_queue_;
265#else
perkj650fdae2017-08-25 05:00:11 -0700266 class Impl;
267 const scoped_refptr<Impl> impl_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200268#endif
269
270 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
271};
272
273} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700274
Henrik Kjellanderc0362762017-06-29 08:03:04 +0200275#endif // WEBRTC_RTC_BASE_TASK_QUEUE_H_