blob: 966b29c40d0c1dc54fa76b6da509003a27a121e2 [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
Henrik Kjellanderc0362762017-06-29 08:03:04 +020011#ifndef WEBRTC_RTC_BASE_TASK_QUEUE_H_
12#define WEBRTC_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>
tommic06b1332016-05-14 11:31:40 -070018
perkj650fdae2017-08-25 05:00:11 -070019#if defined(WEBRTC_MAC)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020020#include <dispatch/dispatch.h>
21#endif
22
kjellandere96c45b2017-06-30 10:45:21 -070023#include "webrtc/rtc_base/constructormagic.h"
24#include "webrtc/rtc_base/criticalsection.h"
kjellandere96c45b2017-06-30 10:45:21 -070025#include "webrtc/rtc_base/scoped_ref_ptr.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020026
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020027namespace rtc {
28
29// Base interface for asynchronously executed tasks.
30// The interface basically consists of a single function, Run(), that executes
31// on the target queue. For more details see the Run() method and TaskQueue.
32class QueuedTask {
33 public:
34 QueuedTask() {}
35 virtual ~QueuedTask() {}
36
37 // Main routine that will run when the task is executed on the desired queue.
38 // The task should return |true| to indicate that it should be deleted or
39 // |false| to indicate that the queue should consider ownership of the task
40 // having been transferred. Returning |false| can be useful if a task has
41 // re-posted itself to a different queue or is otherwise being re-used.
42 virtual bool Run() = 0;
43
44 private:
45 RTC_DISALLOW_COPY_AND_ASSIGN(QueuedTask);
46};
47
48// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
49template <class Closure>
50class ClosureTask : public QueuedTask {
51 public:
52 explicit ClosureTask(const Closure& closure) : closure_(closure) {}
53
54 private:
55 bool Run() override {
56 closure_();
57 return true;
58 }
59
60 Closure closure_;
61};
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:
69 ClosureTaskWithCleanup(const Closure& closure, Cleanup cleanup)
70 : ClosureTask<Closure>(closure), cleanup_(cleanup) {}
71 ~ClosureTaskWithCleanup() { cleanup_(); }
72
73 private:
74 Cleanup cleanup_;
75};
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>
81static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure) {
82 return std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure));
83}
84
85template <class Closure, class Cleanup>
86static std::unique_ptr<QueuedTask> NewClosure(const Closure& closure,
87 const Cleanup& cleanup) {
88 return std::unique_ptr<QueuedTask>(
89 new ClosureTaskWithCleanup<Closure, Cleanup>(closure, cleanup));
90}
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(
120// NewClosure([]() { LOG(INFO) << "The work is done!";}));
121//
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.
danilchap42a70e32017-09-06 01:38:35 -0700152class 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,
192 typename std::enable_if<
193 std::is_copy_constructible<Closure>::value>::type* = nullptr>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200194 void PostTask(const Closure& closure) {
195 PostTask(std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)));
196 }
197
198 // See documentation above for performance expectations.
199 template <class Closure>
200 void PostDelayedTask(const Closure& closure, uint32_t milliseconds) {
201 PostDelayedTask(
202 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(closure)),
203 milliseconds);
204 }
205
206 template <class Closure1, class Closure2>
207 void PostTaskAndReply(const Closure1& task,
208 const Closure2& reply,
209 TaskQueue* reply_queue) {
210 PostTaskAndReply(
211 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
212 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)),
213 reply_queue);
214 }
215
216 template <class Closure>
217 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
218 const Closure& reply) {
219 PostTaskAndReply(std::move(task), std::unique_ptr<QueuedTask>(
220 new ClosureTask<Closure>(reply)));
221 }
222
223 template <class Closure>
224 void PostTaskAndReply(const Closure& task,
225 std::unique_ptr<QueuedTask> reply) {
226 PostTaskAndReply(
227 std::unique_ptr<QueuedTask>(new ClosureTask<Closure>(task)),
228 std::move(reply));
229 }
230
231 template <class Closure1, class Closure2>
232 void PostTaskAndReply(const Closure1& task, const Closure2& reply) {
233 PostTaskAndReply(
234 std::unique_ptr<QueuedTask>(new ClosureTask<Closure1>(task)),
235 std::unique_ptr<QueuedTask>(new ClosureTask<Closure2>(reply)));
236 }
237
238 private:
perkj650fdae2017-08-25 05:00:11 -0700239#if defined(WEBRTC_MAC)
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200240 struct QueueContext;
241 struct TaskContext;
242 struct PostTaskAndReplyContext;
243 dispatch_queue_t queue_;
244 QueueContext* const context_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200245#else
perkj650fdae2017-08-25 05:00:11 -0700246 class Impl;
247 const scoped_refptr<Impl> impl_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200248#endif
249
250 RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
251};
252
253} // namespace rtc
tommic06b1332016-05-14 11:31:40 -0700254
Henrik Kjellanderc0362762017-06-29 08:03:04 +0200255#endif // WEBRTC_RTC_BASE_TASK_QUEUE_H_