blob: 2f247e6038b97bec7736d0826a81a92c1841b238 [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>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020018#include <utility>
tommic06b1332016-05-14 11:31:40 -070019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/constructormagic.h"
21#include "rtc_base/criticalsection.h"
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020022#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/scoped_ref_ptr.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025namespace rtc {
26
27// Base interface for asynchronously executed tasks.
28// The interface basically consists of a single function, Run(), that executes
29// on the target queue. For more details see the Run() method and TaskQueue.
30class QueuedTask {
31 public:
32 QueuedTask() {}
33 virtual ~QueuedTask() {}
34
35 // Main routine that will run when the task is executed on the desired queue.
36 // The task should return |true| to indicate that it should be deleted or
37 // |false| to indicate that the queue should consider ownership of the task
38 // having been transferred. Returning |false| can be useful if a task has
39 // re-posted itself to a different queue or is otherwise being re-used.
40 virtual bool Run() = 0;
41
42 private:
43 RTC_DISALLOW_COPY_AND_ASSIGN(QueuedTask);
44};
45
46// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
47template <class Closure>
48class ClosureTask : public QueuedTask {
49 public:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020050 explicit ClosureTask(Closure&& closure)
51 : closure_(std::forward<Closure>(closure)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020052
53 private:
54 bool Run() override {
55 closure_();
56 return true;
57 }
58
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020059 typename std::remove_const<
60 typename std::remove_reference<Closure>::type>::type closure_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020061};
62
63// Extends ClosureTask to also allow specifying cleanup code.
64// This is useful when using lambdas if guaranteeing cleanup, even if a task
65// was dropped (queue is too full), is required.
66template <class Closure, class Cleanup>
67class ClosureTaskWithCleanup : public ClosureTask<Closure> {
68 public:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020069 ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
70 : ClosureTask<Closure>(std::forward<Closure>(closure)),
71 cleanup_(std::forward<Cleanup>(cleanup)) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020072 ~ClosureTaskWithCleanup() { cleanup_(); }
73
74 private:
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020075 typename std::remove_const<
76 typename std::remove_reference<Cleanup>::type>::type cleanup_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020077};
78
79// Convenience function to construct closures that can be passed directly
80// to methods that support std::unique_ptr<QueuedTask> but not template
81// based parameters.
82template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020083static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure) {
84 return rtc::MakeUnique<ClosureTask<Closure>>(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) {
90 return rtc::MakeUnique<ClosureTaskWithCleanup<Closure, Cleanup>>(
91 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.
danilchap3c6abd22017-09-06 05:46:29 -0700154class RTC_LOCKABLE 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_