You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

301 lines
9.0 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2018 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. #include "rtc_base/task_queue_stdlib.h"
  11. #include <string.h>
  12. #include <algorithm>
  13. #include <map>
  14. #include <memory>
  15. #include <queue>
  16. #include <utility>
  17. #include "absl/strings/string_view.h"
  18. #include "api/task_queue/queued_task.h"
  19. #include "api/task_queue/task_queue_base.h"
  20. #include "rtc_base/checks.h"
  21. #include "rtc_base/critical_section.h"
  22. #include "rtc_base/event.h"
  23. #include "rtc_base/logging.h"
  24. #include "rtc_base/platform_thread.h"
  25. #include "rtc_base/thread_annotations.h"
  26. #include "rtc_base/time_utils.h"
  27. namespace webrtc {
  28. namespace {
  29. rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
  30. TaskQueueFactory::Priority priority) {
  31. switch (priority) {
  32. case TaskQueueFactory::Priority::HIGH:
  33. return rtc::kRealtimePriority;
  34. case TaskQueueFactory::Priority::LOW:
  35. return rtc::kLowPriority;
  36. case TaskQueueFactory::Priority::NORMAL:
  37. return rtc::kNormalPriority;
  38. default:
  39. RTC_NOTREACHED();
  40. return rtc::kNormalPriority;
  41. }
  42. }
  43. class TaskQueueStdlib final : public TaskQueueBase {
  44. public:
  45. TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
  46. ~TaskQueueStdlib() override = default;
  47. void Delete() override;
  48. void PostTask(std::unique_ptr<QueuedTask> task) override;
  49. void PostDelayedTask(std::unique_ptr<QueuedTask> task,
  50. uint32_t milliseconds) override;
  51. private:
  52. using OrderId = uint64_t;
  53. struct DelayedEntryTimeout {
  54. int64_t next_fire_at_ms_{};
  55. OrderId order_{};
  56. bool operator<(const DelayedEntryTimeout& o) const {
  57. return std::tie(next_fire_at_ms_, order_) <
  58. std::tie(o.next_fire_at_ms_, o.order_);
  59. }
  60. };
  61. struct NextTask {
  62. bool final_task_{false};
  63. std::unique_ptr<QueuedTask> run_task_;
  64. int64_t sleep_time_ms_{};
  65. };
  66. NextTask GetNextTask();
  67. static void ThreadMain(void* context);
  68. void ProcessTasks();
  69. void NotifyWake();
  70. // Indicates if the thread has started.
  71. rtc::Event started_;
  72. // Indicates if the thread has stopped.
  73. rtc::Event stopped_;
  74. // Signaled whenever a new task is pending.
  75. rtc::Event flag_notify_;
  76. // Contains the active worker thread assigned to processing
  77. // tasks (including delayed tasks).
  78. rtc::PlatformThread thread_;
  79. rtc::CriticalSection pending_lock_;
  80. // Indicates if the worker thread needs to shutdown now.
  81. bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_){false};
  82. // Holds the next order to use for the next task to be
  83. // put into one of the pending queues.
  84. OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_){};
  85. // The list of all pending tasks that need to be processed in the
  86. // FIFO queue ordering on the worker thread.
  87. std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
  88. RTC_GUARDED_BY(pending_lock_);
  89. // The list of all pending tasks that need to be processed at a future
  90. // time based upon a delay. On the off change the delayed task should
  91. // happen at exactly the same time interval as another task then the
  92. // task is processed based on FIFO ordering. std::priority_queue was
  93. // considered but rejected due to its inability to extract the
  94. // std::unique_ptr out of the queue without the presence of a hack.
  95. std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
  96. RTC_GUARDED_BY(pending_lock_);
  97. };
  98. TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
  99. rtc::ThreadPriority priority)
  100. : started_(/*manual_reset=*/false, /*initially_signaled=*/false),
  101. stopped_(/*manual_reset=*/false, /*initially_signaled=*/false),
  102. flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
  103. thread_(&TaskQueueStdlib::ThreadMain, this, queue_name, priority) {
  104. thread_.Start();
  105. started_.Wait(rtc::Event::kForever);
  106. }
  107. void TaskQueueStdlib::Delete() {
  108. RTC_DCHECK(!IsCurrent());
  109. {
  110. rtc::CritScope lock(&pending_lock_);
  111. thread_should_quit_ = true;
  112. }
  113. NotifyWake();
  114. stopped_.Wait(rtc::Event::kForever);
  115. thread_.Stop();
  116. delete this;
  117. }
  118. void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
  119. {
  120. rtc::CritScope lock(&pending_lock_);
  121. OrderId order = thread_posting_order_++;
  122. pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
  123. order, std::move(task)));
  124. }
  125. NotifyWake();
  126. }
  127. void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
  128. uint32_t milliseconds) {
  129. auto fire_at = rtc::TimeMillis() + milliseconds;
  130. DelayedEntryTimeout delay;
  131. delay.next_fire_at_ms_ = fire_at;
  132. {
  133. rtc::CritScope lock(&pending_lock_);
  134. delay.order_ = ++thread_posting_order_;
  135. delayed_queue_[delay] = std::move(task);
  136. }
  137. NotifyWake();
  138. }
  139. TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
  140. NextTask result{};
  141. auto tick = rtc::TimeMillis();
  142. rtc::CritScope lock(&pending_lock_);
  143. if (thread_should_quit_) {
  144. result.final_task_ = true;
  145. return result;
  146. }
  147. if (delayed_queue_.size() > 0) {
  148. auto delayed_entry = delayed_queue_.begin();
  149. const auto& delay_info = delayed_entry->first;
  150. auto& delay_run = delayed_entry->second;
  151. if (tick >= delay_info.next_fire_at_ms_) {
  152. if (pending_queue_.size() > 0) {
  153. auto& entry = pending_queue_.front();
  154. auto& entry_order = entry.first;
  155. auto& entry_run = entry.second;
  156. if (entry_order < delay_info.order_) {
  157. result.run_task_ = std::move(entry_run);
  158. pending_queue_.pop();
  159. return result;
  160. }
  161. }
  162. result.run_task_ = std::move(delay_run);
  163. delayed_queue_.erase(delayed_entry);
  164. return result;
  165. }
  166. result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
  167. }
  168. if (pending_queue_.size() > 0) {
  169. auto& entry = pending_queue_.front();
  170. result.run_task_ = std::move(entry.second);
  171. pending_queue_.pop();
  172. }
  173. return result;
  174. }
  175. // static
  176. void TaskQueueStdlib::ThreadMain(void* context) {
  177. TaskQueueStdlib* me = static_cast<TaskQueueStdlib*>(context);
  178. CurrentTaskQueueSetter set_current(me);
  179. me->ProcessTasks();
  180. }
  181. void TaskQueueStdlib::ProcessTasks() {
  182. started_.Set();
  183. while (true) {
  184. auto task = GetNextTask();
  185. if (task.final_task_)
  186. break;
  187. if (task.run_task_) {
  188. // process entry immediately then try again
  189. QueuedTask* release_ptr = task.run_task_.release();
  190. if (release_ptr->Run())
  191. delete release_ptr;
  192. // attempt to sleep again
  193. continue;
  194. }
  195. if (0 == task.sleep_time_ms_)
  196. flag_notify_.Wait(rtc::Event::kForever);
  197. else
  198. flag_notify_.Wait(task.sleep_time_ms_);
  199. }
  200. stopped_.Set();
  201. }
  202. void TaskQueueStdlib::NotifyWake() {
  203. // The queue holds pending tasks to complete. Either tasks are to be
  204. // executed immediately or tasks are to be run at some future delayed time.
  205. // For immediate tasks the task queue's thread is busy running the task and
  206. // the thread will not be waiting on the flag_notify_ event. If no immediate
  207. // tasks are available but a delayed task is pending then the thread will be
  208. // waiting on flag_notify_ with a delayed time-out of the nearest timed task
  209. // to run. If no immediate or pending tasks are available, the thread will
  210. // wait on flag_notify_ until signaled that a task has been added (or the
  211. // thread to be told to shutdown).
  212. // In all cases, when a new immediate task, delayed task, or request to
  213. // shutdown the thread is added the flag_notify_ is signaled after. If the
  214. // thread was waiting then the thread will wake up immediately and re-assess
  215. // what task needs to be run next (i.e. run a task now, wait for the nearest
  216. // timed delayed task, or shutdown the thread). If the thread was not waiting
  217. // then the thread will remained signaled to wake up the next time any
  218. // attempt to wait on the flag_notify_ event occurs.
  219. // Any immediate or delayed pending task (or request to shutdown the thread)
  220. // must always be added to the queue prior to signaling flag_notify_ to wake
  221. // up the possibly sleeping thread. This prevents a race condition where the
  222. // thread is notified to wake up but the task queue's thread finds nothing to
  223. // do so it waits once again to be signaled where such a signal may never
  224. // happen.
  225. flag_notify_.Set();
  226. }
  227. class TaskQueueStdlibFactory final : public TaskQueueFactory {
  228. public:
  229. std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
  230. absl::string_view name,
  231. Priority priority) const override {
  232. return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
  233. new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
  234. }
  235. };
  236. } // namespace
  237. std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
  238. return std::make_unique<TaskQueueStdlibFactory>();
  239. }
  240. } // namespace webrtc