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