blob: 12208086649c6878e1c5b87f892ea1a4ca660304 [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
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
18namespace rtc {
19namespace {
20class MockYieldHandler : public YieldInterface {
21 public:
22 MOCK_METHOD0(YieldExecution, void());
23};
24} // namespace
25TEST(YieldPolicyTest, HandlerReceivesYieldSignalWhenSet) {
Mirko Bonadei6a489f22019-04-09 15:11:12 +020026 ::testing::StrictMock<MockYieldHandler> handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010027 {
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
42TEST(YieldPolicyTest, IsThreadLocal) {
43 Event events[3];
44 std::thread other_thread([&]() {
Mirko Bonadei6a489f22019-04-09 15:11:12 +020045 ::testing::StrictMock<MockYieldHandler> local_handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010046 // 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.
Mirko Bonadei6a489f22019-04-09 15:11:12 +020061 ::testing::StrictMock<MockYieldHandler> main_handler;
Sebastian Jansson7a603392019-03-20 16:50:35 +010062 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