1 /*
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 
11 #ifndef RTC_BASE_TASK_QUEUE_H_
12 #define RTC_BASE_TASK_QUEUE_H_
13 
14 #include <stdint.h>
15 
16 #include <memory>
17 #include <utility>
18 
19 #include "absl/memory/memory.h"
20 #include "api/task_queue/queued_task.h"
21 #include "api/task_queue/task_queue_base.h"
22 #include "api/task_queue/task_queue_factory.h"
23 #include "rtc_base/constructor_magic.h"
24 #include "rtc_base/system/rtc_export.h"
25 #include "rtc_base/task_utils/to_queued_task.h"
26 #include "rtc_base/thread_annotations.h"
27 
28 namespace rtc {
29 // Implements a task queue that asynchronously executes tasks in a way that
30 // guarantees that they're executed in FIFO order and that tasks never overlap.
31 // Tasks may always execute on the same worker thread and they may not.
32 // To DCHECK that tasks are executing on a known task queue, use IsCurrent().
33 //
34 // Here are some usage examples:
35 //
36 //   1) Asynchronously running a lambda:
37 //
38 //     class MyClass {
39 //       ...
40 //       TaskQueue queue_("MyQueue");
41 //     };
42 //
43 //     void MyClass::StartWork() {
44 //       queue_.PostTask([]() { Work(); });
45 //     ...
46 //
47 //   2) Posting a custom task on a timer.  The task posts itself again after
48 //      every running:
49 //
50 //     class TimerTask : public QueuedTask {
51 //      public:
52 //       TimerTask() {}
53 //      private:
54 //       bool Run() override {
55 //         ++count_;
56 //         TaskQueueBase::Current()->PostDelayedTask(
57 //             absl::WrapUnique(this), 1000);
58 //         // Ownership has been transferred to the next occurance,
59 //         // so return false to prevent from being deleted now.
60 //         return false;
61 //       }
62 //       int count_ = 0;
63 //     };
64 //     ...
65 //     queue_.PostDelayedTask(std::make_unique<TimerTask>(), 1000);
66 //
67 // For more examples, see task_queue_unittests.cc.
68 //
69 // A note on destruction:
70 //
71 // When a TaskQueue is deleted, pending tasks will not be executed but they will
72 // be deleted.  The deletion of tasks may happen asynchronously after the
73 // TaskQueue itself has been deleted or it may happen synchronously while the
74 // TaskQueue instance is being deleted.  This may vary from one OS to the next
75 // so assumptions about lifetimes of pending tasks should not be made.
76 class RTC_LOCKABLE RTC_EXPORT TaskQueue {
77  public:
78   // TaskQueue priority levels. On some platforms these will map to thread
79   // priorities, on others such as Mac and iOS, GCD queue priorities.
80   using Priority = ::webrtc::TaskQueueFactory::Priority;
81 
82   explicit TaskQueue(std::unique_ptr<webrtc::TaskQueueBase,
83                                      webrtc::TaskQueueDeleter> task_queue);
84   ~TaskQueue();
85 
86   // Used for DCHECKing the current queue.
87   bool IsCurrent() const;
88 
89   // Returns non-owning pointer to the task queue implementation.
Get()90   webrtc::TaskQueueBase* Get() { return impl_; }
91 
92   // TODO(tommi): For better debuggability, implement RTC_FROM_HERE.
93 
94   // Ownership of the task is passed to PostTask.
95   void PostTask(std::unique_ptr<webrtc::QueuedTask> task);
96 
97   // Schedules a task to execute a specified number of milliseconds from when
98   // the call is made. The precision should be considered as "best effort"
99   // and in some cases, such as on Windows when all high precision timers have
100   // been used up, can be off by as much as 15 millseconds (although 8 would be
101   // more likely). This can be mitigated by limiting the use of delayed tasks.
102   void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
103                        uint32_t milliseconds);
104 
105   // std::enable_if is used here to make sure that calls to PostTask() with
106   // std::unique_ptr<SomeClassDerivedFromQueuedTask> would not end up being
107   // caught by this template.
108   template <class Closure,
109             typename std::enable_if<!std::is_convertible<
110                 Closure,
111                 std::unique_ptr<webrtc::QueuedTask>>::value>::type* = nullptr>
PostTask(Closure && closure)112   void PostTask(Closure&& closure) {
113     PostTask(webrtc::ToQueuedTask(std::forward<Closure>(closure)));
114   }
115 
116   // See documentation above for performance expectations.
117   template <class Closure,
118             typename std::enable_if<!std::is_convertible<
119                 Closure,
120                 std::unique_ptr<webrtc::QueuedTask>>::value>::type* = nullptr>
PostDelayedTask(Closure && closure,uint32_t milliseconds)121   void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
122     PostDelayedTask(webrtc::ToQueuedTask(std::forward<Closure>(closure)),
123                     milliseconds);
124   }
125 
126  private:
127   webrtc::TaskQueueBase* const impl_;
128 
129   RTC_DISALLOW_COPY_AND_ASSIGN(TaskQueue);
130 };
131 
132 }  // namespace rtc
133 
134 #endif  // RTC_BASE_TASK_QUEUE_H_
135