blob: e0c622510a15014a329d7268bbb983bfe3a181ed [file] [log] [blame]
Sebastian Jansson7a603392019-03-20 16:50:35 +01001/*
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
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "rtc_base/synchronization/yield_policy.h"
12
Sebastian Jansson7a603392019-03-20 16:50:35 +010013#include <thread> // Not allowed in production per Chromium style guide.
14
15#include "rtc_base/event.h"
Sebastian Jansson7a603392019-03-20 16:50:35 +010016#include "test/gmock.h"
17#include "test/gtest.h"
18
19namespace rtc {
20namespace {
21class MockYieldHandler : public YieldInterface {
22 public:
23 MOCK_METHOD0(YieldExecution, void());
24};
25} // namespace
26TEST(YieldPolicyTest, HandlerReceivesYieldSignalWhenSet) {
Mirko Bonadei6a489f22019-04-09 15:11:12 +020027 ::testing::StrictMock<MockYieldHandler> handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010028 {
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
43TEST(YieldPolicyTest, IsThreadLocal) {
44 Event events[3];
45 std::thread other_thread([&]() {
Mirko Bonadei6a489f22019-04-09 15:11:12 +020046 ::testing::StrictMock<MockYieldHandler> local_handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010047 // 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.
Mirko Bonadei6a489f22019-04-09 15:11:12 +020062 ::testing::StrictMock<MockYieldHandler> main_handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010063 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