blob: 41d6a10cd3280a6f6afcde1f3d5f5be8dfdfba06 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/constructormagic.h"
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020019#include "rtc_base/ptr_util.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) {
82 return rtc::MakeUnique<ClosureTask<Closure>>(std::forward<Closure>(closure));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020083}
84
85template <class Closure, class Cleanup>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020086static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure,
87 Cleanup&& cleanup) {
88 return rtc::MakeUnique<ClosureTaskWithCleanup<Closure, Cleanup>>(
89 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020090}
91
92// Implements a task queue that asynchronously executes tasks in a way that
93// guarantees that they're executed in FIFO order and that tasks never overlap.
94// Tasks may always execute on the same worker thread and they may not.
95// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
96//
97// Here are some usage examples:
98//
99// 1) Asynchronously running a lambda:
100//
101// class MyClass {
102// ...
103// TaskQueue queue_("MyQueue");
104// };
105//
106// void MyClass::StartWork() {
107// queue_.PostTask([]() { Work(); });
108// ...
109//
110// 2) Doing work asynchronously on a worker queue and providing a notification
111// callback on the current queue, when the work has been done:
112//
113// void MyClass::StartWorkAndLetMeKnowWhenDone(
114// std::unique_ptr<QueuedTask> callback) {
115// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
116// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
117// }
118// ...
119// my_class->StartWorkAndLetMeKnowWhenDone(
Mirko Bonadei675513b2017-11-09 11:09:25 +0100120// NewClosure([]() { RTC_LOG(INFO) << "The work is done!";}));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200121//
122// 3) Posting a custom task on a timer. The task posts itself again after
123// every running:
124//
125// class TimerTask : public QueuedTask {
126// public:
127// TimerTask() {}
128// private:
129// bool Run() override {
130// ++count_;
131// TaskQueue::Current()->PostDelayedTask(
132// std::unique_ptr<QueuedTask>(this), 1000);
133// // Ownership has been transferred to the next occurance,
134// // so return false to prevent from being deleted now.
135// return false;
136// }
137// int count_ = 0;
138// };
139// ...
140// queue_.PostDelayedTask(
141// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
142//
143// For more examples, see task_queue_unittests.cc.
144//
145// A note on destruction:
146//
147// When a TaskQueue is deleted, pending tasks will not be executed but they will
148// be deleted. The deletion of tasks may happen asynchronously after the
149// TaskQueue itself has been deleted or it may happen synchronously while the
150// TaskQueue instance is being deleted. This may vary from one OS to the next
151// so assumptions about lifetimes of pending tasks should not be made.
danilchap3c6abd22017-09-06 05:46:29 -0700152class RTC_LOCKABLE TaskQueue {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200153 public:
154 // TaskQueue priority levels. On some platforms these will map to thread
155 // priorities, on others such as Mac and iOS, GCD queue priorities.
156 enum class Priority {
157 NORMAL = 0,
158 HIGH,
159 LOW,
160 };
161
162 explicit TaskQueue(const char* queue_name,
163 Priority priority = Priority::NORMAL);
164 ~TaskQueue();
165
166 static TaskQueue* Current();
167
168 // Used for DCHECKing the current queue.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200169 bool IsCurrent() const;
170
171 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
172
173 // Ownership of the task is passed to PostTask.
174 void PostTask(std::unique_ptr<QueuedTask> task);
175 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
176 std::unique_ptr<QueuedTask> reply,
177 TaskQueue* reply_queue);
178 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
179 std::unique_ptr<QueuedTask> reply);
180
181 // Schedules a task to execute a specified number of milliseconds from when
182 // the call is made. The precision should be considered as "best effort"
183 // and in some cases, such as on Windows when all high precision timers have
184 // been used up, can be off by as much as 15 millseconds (although 8 would be
185 // more likely). This can be mitigated by limiting the use of delayed tasks.
186 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
187
eladalonffe2e142017-08-31 04:36:05 -0700188 // std::enable_if is used here to make sure that calls to PostTask() with
189 // std::unique_ptr<SomeClassDerivedFromQueuedTask> would not end up being
190 // caught by this template.
191 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200192 typename std::enable_if<!std::is_convertible<
193 Closure,
194 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
195 void PostTask(Closure&& closure) {
196 PostTask(NewClosure(std::forward<Closure>(closure)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200197 }
198
199 // See documentation above for performance expectations.
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200200 template <class Closure,
201 typename std::enable_if<!std::is_convertible<
202 Closure,
203 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
204 void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
205 PostDelayedTask(NewClosure(std::forward<Closure>(closure)), milliseconds);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200206 }
207
208 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200209 void PostTaskAndReply(Closure1&& task,
210 Closure2&& reply,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200211 TaskQueue* reply_queue) {
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200212 PostTaskAndReply(NewClosure(std::forward<Closure1>(task)),
213 NewClosure(std::forward<Closure2>(reply)), reply_queue);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200214 }
215
216 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200217 void PostTaskAndReply(std::unique_ptr<QueuedTask> task, Closure&& reply) {
218 PostTaskAndReply(std::move(task), NewClosure(std::forward<Closure>(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200219 }
220
221 template <class Closure>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200222 void PostTaskAndReply(Closure&& task, std::unique_ptr<QueuedTask> reply) {
223 PostTaskAndReply(NewClosure(std::forward<Closure>(task)), std::move(reply));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200224 }
225
226 template <class Closure1, class Closure2>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200227 void PostTaskAndReply(Closure1&& task, Closure2&& reply) {
228 PostTaskAndReply(NewClosure(std::forward(task)),
229 NewClosure(std::forward(reply)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200230 }
231
232 private:
perkj650fdae2017-08-25 05:00:11 -0700233 class Impl;
234 const scoped_refptr<Impl> impl_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235
236 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
237};
238
239} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700240
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200241#endif // RTC_BASE_TASK_QUEUE_H_