blob: b8b307ca6a4058354e4b1b888698848b5394e793 [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 <memory>
eladalonffe2e142017-08-31 04:36:05 -070015#include <type_traits>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020016#include <utility>
tommic06b1332016-05-14 11:31:40 -070017
Karl Wiberg918f50c2018-07-05 11:40:33 +020018#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/constructormagic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/scoped_ref_ptr.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010021#include "rtc_base/thread_annotations.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:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020048 explicit ClosureTask(Closure&& closure)
49 : closure_(std::forward<Closure>(closure)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020050
51 private:
52 bool Run() override {
53 closure_();
54 return true;
55 }
56
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020057 typename std::remove_const<
58 typename std::remove_reference<Closure>::type>::type closure_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020059};
60
61// Extends ClosureTask to also allow specifying cleanup code.
62// This is useful when using lambdas if guaranteeing cleanup, even if a task
63// was dropped (queue is too full), is required.
64template <class Closure, class Cleanup>
65class ClosureTaskWithCleanup : public ClosureTask<Closure> {
66 public:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020067 ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
68 : ClosureTask<Closure>(std::forward<Closure>(closure)),
69 cleanup_(std::forward<Cleanup>(cleanup)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020070 ~ClosureTaskWithCleanup() { cleanup_(); }
71
72 private:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020073 typename std::remove_const<
74 typename std::remove_reference<Cleanup>::type>::type cleanup_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020075};
76
77// Convenience function to construct closures that can be passed directly
78// to methods that support std::unique_ptr<QueuedTask> but not template
79// based parameters.
80template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020081static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020082 return absl::make_unique<ClosureTask<Closure>>(
83 std::forward<Closure>(closure));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084}
85
86template <class Closure, class Cleanup>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020087static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure,
88 Cleanup&& cleanup) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020089 return absl::make_unique<ClosureTaskWithCleanup<Closure, Cleanup>>(
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020090 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091}
92
93// Implements a task queue that asynchronously executes tasks in a way that
94// guarantees that they're executed in FIFO order and that tasks never overlap.
95// Tasks may always execute on the same worker thread and they may not.
96// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
97//
98// Here are some usage examples:
99//
100// 1) Asynchronously running a lambda:
101//
102// class MyClass {
103// ...
104// TaskQueue queue_("MyQueue");
105// };
106//
107// void MyClass::StartWork() {
108// queue_.PostTask([]() { Work(); });
109// ...
110//
111// 2) Doing work asynchronously on a worker queue and providing a notification
112// callback on the current queue, when the work has been done:
113//
114// void MyClass::StartWorkAndLetMeKnowWhenDone(
115// std::unique_ptr<QueuedTask> callback) {
116// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
117// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
118// }
119// ...
120// my_class->StartWorkAndLetMeKnowWhenDone(
Mirko Bonadei675513b2017-11-09 11:09:25 +0100121// NewClosure([]() { RTC_LOG(INFO) << "The work is done!";}));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122//
123// 3) Posting a custom task on a timer. The task posts itself again after
124// every running:
125//
126// class TimerTask : public QueuedTask {
127// public:
128// TimerTask() {}
129// private:
130// bool Run() override {
131// ++count_;
132// TaskQueue::Current()->PostDelayedTask(
133// std::unique_ptr<QueuedTask>(this), 1000);
134// // Ownership has been transferred to the next occurance,
135// // so return false to prevent from being deleted now.
136// return false;
137// }
138// int count_ = 0;
139// };
140// ...
141// queue_.PostDelayedTask(
142// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
143//
144// For more examples, see task_queue_unittests.cc.
145//
146// A note on destruction:
147//
148// When a TaskQueue is deleted, pending tasks will not be executed but they will
149// be deleted. The deletion of tasks may happen asynchronously after the
150// TaskQueue itself has been deleted or it may happen synchronously while the
151// TaskQueue instance is being deleted. This may vary from one OS to the next
152// so assumptions about lifetimes of pending tasks should not be made.
danilchap3c6abd22017-09-06 05:46:29 -0700153class RTC_LOCKABLE TaskQueue {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200154 public:
155 // TaskQueue priority levels. On some platforms these will map to thread
156 // priorities, on others such as Mac and iOS, GCD queue priorities.
157 enum class Priority {
158 NORMAL = 0,
159 HIGH,
160 LOW,
161 };
162
163 explicit TaskQueue(const char* queue_name,
164 Priority priority = Priority::NORMAL);
165 ~TaskQueue();
166
167 static TaskQueue* Current();
168
169 // Used for DCHECKing the current queue.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170 bool IsCurrent() const;
171
172 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
173
174 // Ownership of the task is passed to PostTask.
175 void PostTask(std::unique_ptr<QueuedTask> task);
176 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
177 std::unique_ptr<QueuedTask> reply,
178 TaskQueue* reply_queue);
179 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
180 std::unique_ptr<QueuedTask> reply);
181
182 // Schedules a task to execute a specified number of milliseconds from when
183 // the call is made. The precision should be considered as "best effort"
184 // and in some cases, such as on Windows when all high precision timers have
185 // been used up, can be off by as much as 15 millseconds (although 8 would be
186 // more likely). This can be mitigated by limiting the use of delayed tasks.
187 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
188
eladalonffe2e142017-08-31 04:36:05 -0700189 // std::enable_if is used here to make sure that calls to PostTask() with
190 // std::unique_ptr<SomeClassDerivedFromQueuedTask> would not end up being
191 // caught by this template.
192 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200193 typename std::enable_if<!std::is_convertible<
194 Closure,
195 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
196 void PostTask(Closure&& closure) {
197 PostTask(NewClosure(std::forward<Closure>(closure)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 }
199
200 // See documentation above for performance expectations.
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200201 template <class Closure,
202 typename std::enable_if<!std::is_convertible<
203 Closure,
204 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
205 void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
206 PostDelayedTask(NewClosure(std::forward<Closure>(closure)), milliseconds);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200207 }
208
209 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200210 void PostTaskAndReply(Closure1&& task,
211 Closure2&& reply,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200212 TaskQueue* reply_queue) {
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200213 PostTaskAndReply(NewClosure(std::forward<Closure1>(task)),
214 NewClosure(std::forward<Closure2>(reply)), reply_queue);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215 }
216
217 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200218 void PostTaskAndReply(std::unique_ptr<QueuedTask> task, Closure&& reply) {
219 PostTaskAndReply(std::move(task), NewClosure(std::forward<Closure>(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200220 }
221
222 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200223 void PostTaskAndReply(Closure&& task, std::unique_ptr<QueuedTask> reply) {
224 PostTaskAndReply(NewClosure(std::forward<Closure>(task)), std::move(reply));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200225 }
226
227 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200228 void PostTaskAndReply(Closure1&& task, Closure2&& reply) {
229 PostTaskAndReply(NewClosure(std::forward(task)),
230 NewClosure(std::forward(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200231 }
232
233 private:
perkj650fdae2017-08-25 05:00:11 -0700234 class Impl;
235 const scoped_refptr<Impl> impl_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200236
237 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
238};
239
240} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700241
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200242#endif // RTC_BASE_TASK_QUEUE_H_