blob: 0f2d21995519d2e0d5ef434d19debcc3b8546edc [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
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <stdint.h>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020015#include <memory>
eladalonffe2e142017-08-31 04:36:05 -070016#include <type_traits>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020017#include <utility>
tommic06b1332016-05-14 11:31:40 -070018
Karl Wiberg918f50c2018-07-05 11:40:33 +020019#include "absl/memory/memory.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/scoped_ref_ptr.h"
Mirko Bonadei3d255302018-10-11 10:50:45 +020022#include "rtc_base/system/rtc_export.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010023#include "rtc_base/thread_annotations.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) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020084 return absl::make_unique<ClosureTask<Closure>>(
85 std::forward<Closure>(closure));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020086}
87
88template <class Closure, class Cleanup>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020089static std::unique_ptr<QueuedTask> NewClosure(Closure&& closure,
90 Cleanup&& cleanup) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020091 return absl::make_unique<ClosureTaskWithCleanup<Closure, Cleanup>>(
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020092 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020093}
94
95// Implements a task queue that asynchronously executes tasks in a way that
96// guarantees that they're executed in FIFO order and that tasks never overlap.
97// Tasks may always execute on the same worker thread and they may not.
98// To DCHECK that tasks are executing on a known task queue, use IsCurrent().
99//
100// Here are some usage examples:
101//
102// 1) Asynchronously running a lambda:
103//
104// class MyClass {
105// ...
106// TaskQueue queue_("MyQueue");
107// };
108//
109// void MyClass::StartWork() {
110// queue_.PostTask([]() { Work(); });
111// ...
112//
113// 2) Doing work asynchronously on a worker queue and providing a notification
114// callback on the current queue, when the work has been done:
115//
116// void MyClass::StartWorkAndLetMeKnowWhenDone(
117// std::unique_ptr<QueuedTask> callback) {
118// DCHECK(TaskQueue::Current()) << "Need to be running on a queue";
119// queue_.PostTaskAndReply([]() { Work(); }, std::move(callback));
120// }
121// ...
122// my_class->StartWorkAndLetMeKnowWhenDone(
Mirko Bonadei675513b2017-11-09 11:09:25 +0100123// NewClosure([]() { RTC_LOG(INFO) << "The work is done!";}));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124//
125// 3) Posting a custom task on a timer. The task posts itself again after
126// every running:
127//
128// class TimerTask : public QueuedTask {
129// public:
130// TimerTask() {}
131// private:
132// bool Run() override {
133// ++count_;
134// TaskQueue::Current()->PostDelayedTask(
135// std::unique_ptr<QueuedTask>(this), 1000);
136// // Ownership has been transferred to the next occurance,
137// // so return false to prevent from being deleted now.
138// return false;
139// }
140// int count_ = 0;
141// };
142// ...
143// queue_.PostDelayedTask(
144// std::unique_ptr<QueuedTask>(new TimerTask()), 1000);
145//
146// For more examples, see task_queue_unittests.cc.
147//
148// A note on destruction:
149//
150// When a TaskQueue is deleted, pending tasks will not be executed but they will
151// be deleted. The deletion of tasks may happen asynchronously after the
152// TaskQueue itself has been deleted or it may happen synchronously while the
153// TaskQueue instance is being deleted. This may vary from one OS to the next
154// so assumptions about lifetimes of pending tasks should not be made.
Mirko Bonadei3d255302018-10-11 10:50:45 +0200155class RTC_LOCKABLE RTC_EXPORT TaskQueue {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200156 public:
157 // TaskQueue priority levels. On some platforms these will map to thread
158 // priorities, on others such as Mac and iOS, GCD queue priorities.
159 enum class Priority {
160 NORMAL = 0,
161 HIGH,
162 LOW,
163 };
164
165 explicit TaskQueue(const char* queue_name,
166 Priority priority = Priority::NORMAL);
167 ~TaskQueue();
168
169 static TaskQueue* Current();
170
171 // Used for DCHECKing the current queue.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172 bool IsCurrent() const;
173
174 // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
175
176 // Ownership of the task is passed to PostTask.
177 void PostTask(std::unique_ptr<QueuedTask> task);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200178
179 // Schedules a task to execute a specified number of milliseconds from when
180 // the call is made. The precision should be considered as "best effort"
181 // and in some cases, such as on Windows when all high precision timers have
182 // been used up, can be off by as much as 15 millseconds (although 8 would be
183 // more likely). This can be mitigated by limiting the use of delayed tasks.
184 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
185
eladalonffe2e142017-08-31 04:36:05 -0700186 // std::enable_if is used here to make sure that calls to PostTask() with
187 // std::unique_ptr<SomeClassDerivedFromQueuedTask> would not end up being
188 // caught by this template.
189 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200190 typename std::enable_if<!std::is_convertible<
191 Closure,
192 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
193 void PostTask(Closure&& closure) {
194 PostTask(NewClosure(std::forward<Closure>(closure)));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200195 }
196
197 // See documentation above for performance expectations.
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200198 template <class Closure,
199 typename std::enable_if<!std::is_convertible<
200 Closure,
201 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
202 void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
203 PostDelayedTask(NewClosure(std::forward<Closure>(closure)), milliseconds);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200204 }
205
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200206 private:
perkj650fdae2017-08-25 05:00:11 -0700207 class Impl;
Danil Chapovalov43f39822018-12-05 15:46:58 +0100208 // TODO(danilchap): Remove when external implementaions of TaskQueue remove
209 // these two functions.
210 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
211 std::unique_ptr<QueuedTask> reply,
212 TaskQueue* reply_queue);
213 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
214 std::unique_ptr<QueuedTask> reply);
Yves Gerey3e707812018-11-28 16:47:49 +0100215
perkj650fdae2017-08-25 05:00:11 -0700216 const scoped_refptr<Impl> impl_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217
218 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
219};
220
221} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700222
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200223#endif // RTC_BASE_TASK_QUEUE_H_