xref: /aosp_15_r20/external/webrtc/rtc_base/synchronization/yield_policy_unittest.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2019 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 #include "rtc_base/synchronization/yield_policy.h"
12 
13 #include <thread>  // Not allowed in production per Chromium style guide.
14 
15 #include "rtc_base/event.h"
16 #include "test/gmock.h"
17 #include "test/gtest.h"
18 
19 namespace rtc {
20 namespace {
21 class MockYieldHandler : public YieldInterface {
22  public:
23   MOCK_METHOD(void, YieldExecution, (), (override));
24 };
25 }  // namespace
TEST(YieldPolicyTest,HandlerReceivesYieldSignalWhenSet)26 TEST(YieldPolicyTest, HandlerReceivesYieldSignalWhenSet) {
27   ::testing::StrictMock<MockYieldHandler> handler;
28   {
29     Event event;
30     EXPECT_CALL(handler, YieldExecution()).Times(1);
31     ScopedYieldPolicy policy(&handler);
32     event.Set();
33     event.Wait(Event::kForever);
34   }
35   {
36     Event event;
37     EXPECT_CALL(handler, YieldExecution()).Times(0);
38     event.Set();
39     event.Wait(Event::kForever);
40   }
41 }
42 
TEST(YieldPolicyTest,IsThreadLocal)43 TEST(YieldPolicyTest, IsThreadLocal) {
44   Event events[3];
45   std::thread other_thread([&]() {
46     ::testing::StrictMock<MockYieldHandler> local_handler;
47     // The local handler is never called as we never Wait on this thread.
48     EXPECT_CALL(local_handler, YieldExecution()).Times(0);
49     ScopedYieldPolicy policy(&local_handler);
50     events[0].Set();
51     events[1].Set();
52     events[2].Set();
53   });
54 
55   // Waiting until the other thread has entered the scoped policy.
56   events[0].Wait(Event::kForever);
57   // Wait on this thread should not trigger the handler of that policy as it's
58   // thread local.
59   events[1].Wait(Event::kForever);
60 
61   // We can set a policy that's active on this thread independently.
62   ::testing::StrictMock<MockYieldHandler> main_handler;
63   EXPECT_CALL(main_handler, YieldExecution()).Times(1);
64   ScopedYieldPolicy policy(&main_handler);
65   events[2].Wait(Event::kForever);
66   other_thread.join();
67 }
68 }  // namespace rtc
69