blob: 888e203967cd365ad082b33e809dc1a749c16d8b [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"
Mirko Bonadei99eea422018-10-08 11:10:10 +000021#include "rtc_base/system/rtc_export.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010022#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020023
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024namespace rtc {
25
26// Base interface for asynchronously executed tasks.
27// The interface basically consists of a single function, Run(), that executes
28// on the target queue. For more details see the Run() method and TaskQueue.
29class QueuedTask {
30 public:
31 QueuedTask() {}
32 virtual ~QueuedTask() {}
33
34 // Main routine that will run when the task is executed on the desired queue.
35 // The task should return |true| to indicate that it should be deleted or
36 // |false| to indicate that the queue should consider ownership of the task
37 // having been transferred. Returning |false| can be useful if a task has
38 // re-posted itself to a different queue or is otherwise being re-used.
39 virtual bool Run() = 0;
40
41 private:
42 RTC_DISALLOW_COPY_AND_ASSIGN(QueuedTask);
43};
44
45// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
46template <class Closure>
47class ClosureTask : public QueuedTask {
48 public:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020049 explicit ClosureTask(Closure&& closure)
50 : closure_(std::forward<Closure>(closure)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020051
52 private:
53 bool Run() override {
54 closure_();
55 return true;
56 }
57
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020058 typename std::remove_const<
59 typename std::remove_reference<Closure>::type>::type closure_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020060};
61
62// Extends ClosureTask to also allow specifying cleanup code.
63// This is useful when using lambdas if guaranteeing cleanup, even if a task
64// was dropped (queue is too full), is required.
65template <class Closure, class Cleanup>
66class ClosureTaskWithCleanup : public ClosureTask<Closure> {
67 public:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020068 ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
69 : ClosureTask<Closure>(std::forward<Closure>(closure)),
70 cleanup_(std::forward<Cleanup>(cleanup)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071 ~ClosureTaskWithCleanup() { cleanup_(); }
72
73 private:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020074 typename std::remove_const<
75 typename std::remove_reference<Cleanup>::type>::type cleanup_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020076};
77
78// Convenience function to construct closures that can be passed directly
79// to methods that support std::unique_ptr<QueuedTask> but not template
80// based parameters.
81template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020082static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020083 return absl::make_unique<ClosureTask<Closure>>(
84 std::forward<Closure>(closure));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020085}
86
87template <class Closure, class Cleanup>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020088static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure,
89 Cleanup&& cleanup) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020090 return absl::make_unique<ClosureTaskWithCleanup<Closure, Cleanup>>(
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020091 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020092}
93
94// Implements a task queue that asynchronously executes tasks in a way that
95// guarantees that they're executed in FIFO order and that tasks never overlap.
96// Tasks may always execute on the same worker thread and they may not.
97// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
98//
99// Here are some usage examples:
100//
101// 1) Asynchronously running a lambda:
102//
103// class MyClass {
104// ...
105// TaskQueue queue_("MyQueue");
106// };
107//
108// void MyClass::StartWork() {
109// queue_.PostTask([]() { Work(); });
110// ...
111//
112// 2) Doing work asynchronously on a worker queue and providing a notification
113// callback on the current queue, when the work has been done:
114//
115// void MyClass::StartWorkAndLetMeKnowWhenDone(
116// std::unique_ptr<QueuedTask> callback) {
117// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
118// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
119// }
120// ...
121// my_class->StartWorkAndLetMeKnowWhenDone(
Mirko Bonadei675513b2017-11-09 11:09:25 +0100122// NewClosure([]() { RTC_LOG(INFO) << "The work is done!";}));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123//
124// 3) Posting a custom task on a timer. The task posts itself again after
125// every running:
126//
127// class TimerTask : public QueuedTask {
128// public:
129// TimerTask() {}
130// private:
131// bool Run() override {
132// ++count_;
133// TaskQueue::Current()->PostDelayedTask(
134// std::unique_ptr<QueuedTask>(this), 1000);
135// // Ownership has been transferred to the next occurance,
136// // so return false to prevent from being deleted now.
137// return false;
138// }
139// int count_ = 0;
140// };
141// ...
142// queue_.PostDelayedTask(
143// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
144//
145// For more examples, see task_queue_unittests.cc.
146//
147// A note on destruction:
148//
149// When a TaskQueue is deleted, pending tasks will not be executed but they will
150// be deleted. The deletion of tasks may happen asynchronously after the
151// TaskQueue itself has been deleted or it may happen synchronously while the
152// TaskQueue instance is being deleted. This may vary from one OS to the next
153// so assumptions about lifetimes of pending tasks should not be made.
Mirko Bonadei99eea422018-10-08 11:10:10 +0000154class RTC_LOCKABLE RTC_EXPORT TaskQueue {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155 public:
156 // TaskQueue priority levels. On some platforms these will map to thread
157 // priorities, on others such as Mac and iOS, GCD queue priorities.
158 enum class Priority {
159 NORMAL = 0,
160 HIGH,
161 LOW,
162 };
163
164 explicit TaskQueue(const char* queue_name,
165 Priority priority = Priority::NORMAL);
166 ~TaskQueue();
167
168 static TaskQueue* Current();
169
170 // Used for DCHECKing the current queue.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200171 bool IsCurrent() const;
172
173 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
174
175 // Ownership of the task is passed to PostTask.
176 void PostTask(std::unique_ptr<QueuedTask> task);
177 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
178 std::unique_ptr<QueuedTask> reply,
179 TaskQueue* reply_queue);
180 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
181 std::unique_ptr<QueuedTask> reply);
182
183 // Schedules a task to execute a specified number of milliseconds from when
184 // the call is made. The precision should be considered as "best effort"
185 // and in some cases, such as on Windows when all high precision timers have
186 // been used up, can be off by as much as 15 millseconds (although 8 would be
187 // more likely). This can be mitigated by limiting the use of delayed tasks.
188 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
189
eladalonffe2e142017-08-31 04:36:05 -0700190 // std::enable_if is used here to make sure that calls to PostTask() with
191 // std::unique_ptr<SomeClassDerivedFromQueuedTask> would not end up being
192 // caught by this template.
193 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200194 typename std::enable_if<!std::is_convertible<
195 Closure,
196 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
197 void PostTask(Closure&& closure) {
198 PostTask(NewClosure(std::forward<Closure>(closure)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200199 }
200
201 // See documentation above for performance expectations.
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200202 template <class Closure,
203 typename std::enable_if<!std::is_convertible<
204 Closure,
205 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
206 void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
207 PostDelayedTask(NewClosure(std::forward<Closure>(closure)), milliseconds);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200208 }
209
210 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200211 void PostTaskAndReply(Closure1&& task,
212 Closure2&& reply,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200213 TaskQueue* reply_queue) {
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200214 PostTaskAndReply(NewClosure(std::forward<Closure1>(task)),
215 NewClosure(std::forward<Closure2>(reply)), reply_queue);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200216 }
217
218 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200219 void PostTaskAndReply(std::unique_ptr<QueuedTask> task, Closure&& reply) {
220 PostTaskAndReply(std::move(task), NewClosure(std::forward<Closure>(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200221 }
222
223 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200224 void PostTaskAndReply(Closure&& task, std::unique_ptr<QueuedTask> reply) {
225 PostTaskAndReply(NewClosure(std::forward<Closure>(task)), std::move(reply));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200226 }
227
228 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200229 void PostTaskAndReply(Closure1&& task, Closure2&& reply) {
230 PostTaskAndReply(NewClosure(std::forward(task)),
231 NewClosure(std::forward(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 }
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_