xref: /aosp_15_r20/external/webrtc/rtc_base/task_queue_for_test.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
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 
11 #ifndef RTC_BASE_TASK_QUEUE_FOR_TEST_H_
12 #define RTC_BASE_TASK_QUEUE_FOR_TEST_H_
13 
14 #include <utility>
15 
16 #include "absl/cleanup/cleanup.h"
17 #include "absl/strings/string_view.h"
18 #include "api/function_view.h"
19 #include "api/task_queue/task_queue_base.h"
20 #include "rtc_base/checks.h"
21 #include "rtc_base/event.h"
22 #include "rtc_base/task_queue.h"
23 #include "rtc_base/thread_annotations.h"
24 
25 namespace webrtc {
26 
SendTask(TaskQueueBase * task_queue,rtc::FunctionView<void ()> task)27 inline void SendTask(TaskQueueBase* task_queue,
28                      rtc::FunctionView<void()> task) {
29   if (task_queue->IsCurrent()) {
30     task();
31     return;
32   }
33 
34   rtc::Event event;
35   absl::Cleanup cleanup = [&event] { event.Set(); };
36   task_queue->PostTask([task, cleanup = std::move(cleanup)] { task(); });
37   RTC_CHECK(event.Wait(/*give_up_after=*/rtc::Event::kForever,
38                        /*warn_after=*/TimeDelta::Seconds(10)));
39 }
40 
41 class RTC_LOCKABLE TaskQueueForTest : public rtc::TaskQueue {
42  public:
43   using rtc::TaskQueue::TaskQueue;
44   explicit TaskQueueForTest(absl::string_view name = "TestQueue",
45                             Priority priority = Priority::NORMAL);
46   TaskQueueForTest(const TaskQueueForTest&) = delete;
47   TaskQueueForTest& operator=(const TaskQueueForTest&) = delete;
48   ~TaskQueueForTest() = default;
49 
50   // A convenience, test-only method that blocks the current thread while
51   // a task executes on the task queue.
SendTask(rtc::FunctionView<void ()> task)52   void SendTask(rtc::FunctionView<void()> task) {
53     ::webrtc::SendTask(Get(), task);
54   }
55 
56   // Wait for the completion of all tasks posted prior to the
57   // WaitForPreviouslyPostedTasks() call.
WaitForPreviouslyPostedTasks()58   void WaitForPreviouslyPostedTasks() {
59     RTC_DCHECK(!Get()->IsCurrent());
60     // Post an empty task on the queue and wait for it to finish, to ensure
61     // that all already posted tasks on the queue get executed.
62     SendTask([]() {});
63   }
64 };
65 
66 }  // namespace webrtc
67 
68 #endif  // RTC_BASE_TASK_QUEUE_FOR_TEST_H_
69