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