blob: 32589b3216cf2037f89949a76e3b9f8af85f6443 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 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/thread.h"
12
kwibergbfefb032016-05-01 14:53:46 -070013#include <memory>
14
Ali Tofigh83db78e2022-08-23 12:57:16 +020015#include "api/field_trials_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010016#include "api/task_queue/task_queue_factory.h"
17#include "api/task_queue/task_queue_test.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020018#include "api/units/time_delta.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/async_invoker.h"
20#include "rtc_base/async_udp_socket.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020021#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/event.h"
Danil Chapovalov207f8532022-08-24 12:19:46 +020023#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "rtc_base/gunit.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010025#include "rtc_base/internal/default_socket_server.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/null_socket_server.h"
27#include "rtc_base/physical_socket_server.h"
28#include "rtc_base/socket_address.h"
Markus Handell4ab7dde2020-07-10 13:23:25 +020029#include "rtc_base/synchronization/mutex.h"
Artem Titove41c4332018-07-25 15:04:28 +020030#include "rtc_base/third_party/sigslot/sigslot.h"
Danil Chapovalov207f8532022-08-24 12:19:46 +020031#include "test/gmock.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010032#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033
34#if defined(WEBRTC_WIN)
35#include <comdef.h> // NOLINT
Markus Handell4ab7dde2020-07-10 13:23:25 +020036
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037#endif
38
Mirko Bonadeie10b1632018-12-11 18:43:40 +010039namespace rtc {
40namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041
Danil Chapovalov207f8532022-08-24 12:19:46 +020042using ::testing::ElementsAre;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020043using ::webrtc::TimeDelta;
Sebastian Jansson73387822020-01-16 11:15:35 +010044
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045// Generates a sequence of numbers (collaboratively).
46class TestGenerator {
47 public:
48 TestGenerator() : last(0), count(0) {}
49
50 int Next(int prev) {
51 int result = prev + last;
52 last = result;
53 count += 1;
54 return result;
55 }
56
57 int last;
58 int count;
59};
60
61struct TestMessage : public MessageData {
62 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
64 int value;
65};
66
67// Receives on a socket and sends by posting messages.
68class SocketClient : public TestGenerator, public sigslot::has_slots<> {
69 public:
Niels Möllerd0b88792021-08-12 10:32:30 +020070 SocketClient(Socket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +020071 const SocketAddress& addr,
72 Thread* post_thread,
73 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074 : socket_(AsyncUDPSocket::Create(socket, addr)),
75 post_thread_(post_thread),
76 post_handler_(phandler) {
77 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
78 }
79
Steve Anton9de3aac2017-10-24 10:08:26 -070080 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081
82 SocketAddress address() const { return socket_->GetLocalAddress(); }
83
Yves Gerey665174f2018-06-19 15:03:05 +020084 void OnPacket(AsyncPacketSocket* socket,
85 const char* buf,
86 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010088 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020089 EXPECT_EQ(size, sizeof(uint32_t));
90 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
91 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070093 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
94 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095 }
96
97 private:
98 AsyncUDPSocket* socket_;
99 Thread* post_thread_;
100 MessageHandler* post_handler_;
101};
102
103// Receives messages and sends on a socket.
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200104class MessageClient : public MessageHandlerAutoCleanup, public TestGenerator {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200106 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107
Steve Anton9de3aac2017-10-24 10:08:26 -0700108 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109
Steve Anton9de3aac2017-10-24 10:08:26 -0700110 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
112 int result = Next(msg->value);
113 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
114 delete msg;
115 }
116
117 private:
118 Socket* socket_;
119};
120
deadbeefaea92932017-05-23 12:55:03 -0700121class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122 public:
tommie7251592017-07-14 14:44:46 -0700123 CustomThread()
124 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700125 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000127
Yves Gerey665174f2018-06-19 15:03:05 +0200128 bool WrapCurrent() { return Thread::WrapCurrent(); }
129 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130};
131
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132// A thread that does nothing when it runs and signals an event
133// when it is destroyed.
134class SignalWhenDestroyedThread : public Thread {
135 public:
136 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700137 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
138 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139
Steve Anton9de3aac2017-10-24 10:08:26 -0700140 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 Stop();
142 event_->Set();
143 }
144
Steve Anton9de3aac2017-10-24 10:08:26 -0700145 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146 // Do nothing.
147 }
148
149 private:
150 Event* event_;
151};
152
nissed9b75be2015-11-16 00:54:07 -0800153// A bool wrapped in a mutex, to avoid data races. Using a volatile
154// bool should be sufficient for correct code ("eventual consistency"
155// between caches is sufficient), but we can't tell the compiler about
156// that, and then tsan complains about a data race.
157
158// See also discussion at
159// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
160
161// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
162// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700163// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800164// performance critical, use a plain critical section for the time
165// being.
166
167class AtomicBool {
168 public:
169 explicit AtomicBool(bool value = false) : flag_(value) {}
170 AtomicBool& operator=(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200171 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800172 flag_ = value;
173 return *this;
174 }
175 bool get() const {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200176 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800177 return flag_;
178 }
179
180 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200181 mutable webrtc::Mutex mutex_;
nissed9b75be2015-11-16 00:54:07 -0800182 bool flag_;
183};
184
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185// Function objects to test Thread::Invoke.
186struct FunctorA {
187 int operator()() { return 42; }
188};
189class FunctorB {
190 public:
nissed9b75be2015-11-16 00:54:07 -0800191 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200192 void operator()() {
193 if (flag_)
194 *flag_ = true;
195 }
196
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197 private:
nissed9b75be2015-11-16 00:54:07 -0800198 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199};
200struct FunctorC {
201 int operator()() {
202 Thread::Current()->ProcessMessages(50);
203 return 24;
204 }
205};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700206struct FunctorD {
207 public:
208 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
209 FunctorD(FunctorD&&) = default;
Byoungchan Lee14af7622022-01-12 05:24:58 +0900210
211 FunctorD(const FunctorD&) = delete;
212 FunctorD& operator=(const FunctorD&) = delete;
213
Cameron Pickettd132ce12018-03-12 16:07:37 -0700214 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200215 void operator()() {
216 if (flag_)
217 *flag_ = true;
218 }
219
Cameron Pickettd132ce12018-03-12 16:07:37 -0700220 private:
221 AtomicBool* flag_;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700222};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223
224// See: https://code.google.com/p/webrtc/issues/detail?id=2409
225TEST(ThreadTest, DISABLED_Main) {
226 const SocketAddress addr("127.0.0.1", 0);
227
228 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700229 auto th1 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200230 Socket* socket = th1->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700231 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232
233 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700234 auto th2 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200235 Socket* asocket =
236 th2->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700237 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238
239 socket->Connect(sock_client.address());
240
tommie7251592017-07-14 14:44:46 -0700241 th1->Start();
242 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243
244 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700245 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246
247 // Give the clients a little while to run.
248 // Messages will be processed at 100, 300, 500, 700, 900.
249 Thread* th_main = Thread::Current();
250 th_main->ProcessMessages(1000);
251
252 // Stop the sending client. Give the receiver a bit longer to run, in case
253 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700254 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700256 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257
258 // Make sure the results were correct
259 EXPECT_EQ(5, msg_client.count);
260 EXPECT_EQ(34, msg_client.last);
261 EXPECT_EQ(5, sock_client.count);
262 EXPECT_EQ(55, sock_client.last);
263}
264
Tommife041642021-04-07 10:08:28 +0200265TEST(ThreadTest, CountBlockingCalls) {
Niels Möller83830f32022-05-20 09:12:57 +0200266 rtc::AutoThread current;
267
Tommife041642021-04-07 10:08:28 +0200268 // When the test runs, this will print out:
269 // (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
270 RTC_LOG_THREAD_BLOCK_COUNT();
271#if RTC_DCHECK_IS_ON
Tommife041642021-04-07 10:08:28 +0200272 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
273 [&](uint32_t actual_block, uint32_t could_block) {
274 EXPECT_EQ(1u, actual_block);
275 EXPECT_EQ(1u, could_block);
276 });
277
278 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
279 EXPECT_EQ(0u, blocked_calls.GetCouldBeBlockingCallCount());
280 EXPECT_EQ(0u, blocked_calls.GetTotalBlockedCallCount());
281
282 // Test invoking on the current thread. This should not count as an 'actual'
283 // invoke, but should still count as an invoke that could block since we
284 // that the call to Invoke serves a purpose in some configurations (and should
285 // not be used a general way to call methods on the same thread).
Niels Möller83830f32022-05-20 09:12:57 +0200286 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tommife041642021-04-07 10:08:28 +0200287 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
288 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
289 EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
290
291 // Create a new thread to invoke on.
292 auto thread = Thread::CreateWithSocketServer();
293 thread->Start();
294 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, []() { return 42; }));
295 EXPECT_EQ(1u, blocked_calls.GetBlockingCallCount());
296 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
297 EXPECT_EQ(2u, blocked_calls.GetTotalBlockedCallCount());
298 thread->Stop();
299 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2);
300#else
301 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
302 RTC_LOG(LS_INFO) << "Test not active in this config";
303#endif
304}
305
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200306#if RTC_DCHECK_IS_ON
307TEST(ThreadTest, CountBlockingCallsOneCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200308 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200309 bool was_called_back = false;
310 {
311 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
312 [&](uint32_t actual_block, uint32_t could_block) {
313 was_called_back = true;
314 });
Niels Möller83830f32022-05-20 09:12:57 +0200315 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200316 }
317 EXPECT_TRUE(was_called_back);
318}
319
320TEST(ThreadTest, CountBlockingCallsSkipCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200321 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200322 bool was_called_back = false;
323 {
324 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
325 [&](uint32_t actual_block, uint32_t could_block) {
326 was_called_back = true;
327 });
328 // Changed `blocked_calls` to not issue the callback if there are 1 or
329 // fewer blocking calls (i.e. we set the minimum required number to 2).
330 blocked_calls.set_minimum_call_count_for_callback(2);
Niels Möller83830f32022-05-20 09:12:57 +0200331 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200332 }
333 // We should not have gotten a call back.
334 EXPECT_FALSE(was_called_back);
335}
336#endif
337
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338// Test that setting thread names doesn't cause a malfunction.
339// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000340TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 // Default name
tommie7251592017-07-14 14:44:46 -0700342 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343 EXPECT_TRUE(thread->Start());
344 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700346 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800347 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348 EXPECT_TRUE(thread->Start());
349 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350 // Really long name
tommie7251592017-07-14 14:44:46 -0700351 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
353 EXPECT_TRUE(thread->Start());
354 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355}
356
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000357TEST(ThreadTest, Wrap) {
358 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200359 ThreadManager::Instance()->SetCurrentThread(nullptr);
360
361 {
362 CustomThread cthread;
363 EXPECT_TRUE(cthread.WrapCurrent());
364 EXPECT_EQ(&cthread, Thread::Current());
365 EXPECT_TRUE(cthread.RunningForTest());
366 EXPECT_FALSE(cthread.IsOwned());
367 cthread.UnwrapCurrent();
368 EXPECT_FALSE(cthread.RunningForTest());
369 }
370 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371}
372
Mirko Bonadei481e3452021-07-30 13:57:25 +0200373#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200374TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
Niels Möller83830f32022-05-20 09:12:57 +0200375 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200376 // Create and start the thread.
377 auto thread1 = Thread::CreateWithSocketServer();
378 auto thread2 = Thread::CreateWithSocketServer();
379
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200380 thread1->PostTask(
381 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200382 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200383}
384
385TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
Niels Möller83830f32022-05-20 09:12:57 +0200386 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200387 // Create and start the thread.
388 auto thread1 = Thread::CreateWithSocketServer();
389 auto thread2 = Thread::CreateWithSocketServer();
390 auto thread3 = Thread::CreateWithSocketServer();
391 auto thread4 = Thread::CreateWithSocketServer();
392
393 thread1->AllowInvokesToThread(thread2.get());
394 thread1->AllowInvokesToThread(thread3.get());
395
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200396 thread1->PostTask([&]() {
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200397 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
398 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
399 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200400 });
Niels Möller83830f32022-05-20 09:12:57 +0200401 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200402}
403
404TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
Niels Möller83830f32022-05-20 09:12:57 +0200405 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200406 // Create and start the thread.
407 auto thread1 = Thread::CreateWithSocketServer();
408 auto thread2 = Thread::CreateWithSocketServer();
409
410 thread1->DisallowAllInvokes();
411
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200412 thread1->PostTask(
413 [&]() { EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200414 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200415}
Mirko Bonadei481e3452021-07-30 13:57:25 +0200416#endif // (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200417
418TEST(ThreadTest, InvokesAllowedByDefault) {
Niels Möller83830f32022-05-20 09:12:57 +0200419 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200420 // Create and start the thread.
421 auto thread1 = Thread::CreateWithSocketServer();
422 auto thread2 = Thread::CreateWithSocketServer();
423
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200424 thread1->PostTask(
425 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200426 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200427}
428
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000429TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000430 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700431 auto thread = Thread::CreateWithSocketServer();
432 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700434 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800435 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000436 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700437 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800438 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 // Try calling bare functions.
440 struct LocalFuncs {
441 static int Func1() { return 999; }
442 static void Func2() {}
443 };
tommie7251592017-07-14 14:44:46 -0700444 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
445 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446}
447
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000448// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100449// not deadlock but crash.
450#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
451TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200452 GTEST_FLAG_SET(death_test_style, "threadsafe");
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000453 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100454 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700455 auto other_thread = Thread::CreateWithSocketServer();
456 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100457 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
458 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
459 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000460}
461
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100462TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200463 GTEST_FLAG_SET(death_test_style, "threadsafe");
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100464 AutoThread thread;
465 Thread* first = Thread::Current();
466
467 auto second = Thread::Create();
468 second->Start();
469 auto third = Thread::Create();
470 third->Start();
471
472 second->Invoke<void>(RTC_FROM_HERE, [&] {
473 third->Invoke<void>(RTC_FROM_HERE, [&] {
474 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
475 });
476 });
477}
478
479#endif
480
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000481// Verifies that if thread A invokes a call on thread B and thread C is trying
482// to invoke A at the same time, thread A does not handle C's invoke while
483// invoking B.
484TEST(ThreadTest, ThreeThreadsInvoke) {
485 AutoThread thread;
486 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700487 auto thread_b = Thread::CreateWithSocketServer();
488 auto thread_c = Thread::CreateWithSocketServer();
489 thread_b->Start();
490 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000491
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000492 class LockedBool {
493 public:
494 explicit LockedBool(bool value) : value_(value) {}
495
496 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200497 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000498 value_ = value;
499 }
500
501 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200502 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000503 return value_;
504 }
505
506 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200507 webrtc::Mutex mutex_;
508 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000509 };
510
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000511 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000512 static void Set(LockedBool* out) { out->Set(true); }
513 static void InvokeSet(Thread* thread, LockedBool* out) {
Niels Möller1a29a5d2021-01-18 11:35:23 +0100514 thread->Invoke<void>(RTC_FROM_HERE, [out] { Set(out); });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000515 }
516
Artem Titov96e3b992021-07-26 16:03:14 +0200517 // Set `out` true and call InvokeSet on `thread`.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000518 static void SetAndInvokeSet(LockedBool* out,
519 Thread* thread,
520 LockedBool* out_inner) {
521 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000522 InvokeSet(thread, out_inner);
523 }
524
Artem Titov96e3b992021-07-26 16:03:14 +0200525 // Asynchronously invoke SetAndInvokeSet on `thread1` and wait until
526 // `thread1` starts the call.
Niels Möller0694ce72021-05-03 16:03:22 +0200527 static void AsyncInvokeSetAndWait(DEPRECATED_AsyncInvoker* invoker,
deadbeef162cb532017-02-23 17:10:07 -0800528 Thread* thread1,
529 Thread* thread2,
530 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000531 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000532
deadbeef162cb532017-02-23 17:10:07 -0800533 invoker->AsyncInvoke<void>(
Niels Möller1a29a5d2021-01-18 11:35:23 +0100534 RTC_FROM_HERE, thread1, [&async_invoked, thread2, out] {
535 SetAndInvokeSet(&async_invoked, thread2, out);
536 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000537
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000538 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000539 }
540 };
541
Niels Möller0694ce72021-05-03 16:03:22 +0200542 DEPRECATED_AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000543 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000544
545 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
546 // Thread B returns when C receives the call and C should be blocked until A
547 // starts to process messages.
Niels Möller1a29a5d2021-01-18 11:35:23 +0100548 Thread* thread_c_ptr = thread_c.get();
549 thread_b->Invoke<void>(
550 RTC_FROM_HERE, [&invoker, thread_c_ptr, thread_a, &thread_a_called] {
551 LocalFuncs::AsyncInvokeSetAndWait(&invoker, thread_c_ptr, thread_a,
552 &thread_a_called);
553 });
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000554 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000555
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000556 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000557}
558
Sebastian Jansson73387822020-01-16 11:15:35 +0100559class ThreadQueueTest : public ::testing::Test, public Thread {
560 public:
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200561 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {
562 RTC_DCHECK(Thread::Current() == nullptr);
563 ThreadManager::Instance()->SetCurrentThread(this);
564 }
565 ~ThreadQueueTest() { ThreadManager::Instance()->SetCurrentThread(nullptr); }
Sebastian Jansson73387822020-01-16 11:15:35 +0100566 bool IsLocked_Worker() {
567 if (!CritForTest()->TryEnter()) {
568 return true;
569 }
570 CritForTest()->Leave();
571 return false;
572 }
573 bool IsLocked() {
574 // We have to do this on a worker thread, or else the TryEnter will
575 // succeed, since our critical sections are reentrant.
576 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
577 worker->Start();
Niels Möller1a29a5d2021-01-18 11:35:23 +0100578 return worker->Invoke<bool>(RTC_FROM_HERE,
579 [this] { return IsLocked_Worker(); });
Sebastian Jansson73387822020-01-16 11:15:35 +0100580 }
581};
582
583struct DeletedLockChecker {
584 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
585 : test(test), was_locked(was_locked), deleted(deleted) {}
586 ~DeletedLockChecker() {
587 *deleted = true;
588 *was_locked = test->IsLocked();
589 }
590 ThreadQueueTest* test;
591 bool* was_locked;
592 bool* deleted;
593};
594
Danil Chapovalov207f8532022-08-24 12:19:46 +0200595static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(
596 FakeClock& clock,
597 Thread& q) {
598 std::vector<int> run_order;
599
600 Event done;
Sebastian Jansson73387822020-01-16 11:15:35 +0100601 int64_t now = TimeMillis();
Danil Chapovalov207f8532022-08-24 12:19:46 +0200602 q.PostDelayedTask([&] { run_order.push_back(3); }, TimeDelta::Millis(3));
603 q.PostDelayedTask([&] { run_order.push_back(0); }, TimeDelta::Millis(1));
604 q.PostDelayedTask([&] { run_order.push_back(1); }, TimeDelta::Millis(2));
605 q.PostDelayedTask([&] { run_order.push_back(4); }, TimeDelta::Millis(3));
606 q.PostDelayedTask([&] { run_order.push_back(2); }, TimeDelta::Millis(2));
607 q.PostDelayedTask([&] { done.Set(); }, TimeDelta::Millis(4));
608 // Validate time was frozen while tasks were posted.
609 RTC_DCHECK_EQ(TimeMillis(), now);
Sebastian Jansson73387822020-01-16 11:15:35 +0100610
Danil Chapovalov207f8532022-08-24 12:19:46 +0200611 // Change time to make all tasks ready to run and wait for them.
612 clock.AdvanceTime(TimeDelta::Millis(4));
613 ASSERT_TRUE(done.Wait(TimeDelta::Seconds(1)));
Sebastian Jansson73387822020-01-16 11:15:35 +0100614
Danil Chapovalov207f8532022-08-24 12:19:46 +0200615 EXPECT_THAT(run_order, ElementsAre(0, 1, 2, 3, 4));
Sebastian Jansson73387822020-01-16 11:15:35 +0100616}
617
618TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Danil Chapovalov207f8532022-08-24 12:19:46 +0200619 ScopedBaseFakeClock clock;
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100620 Thread q(CreateDefaultSocketServer(), true);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200621 q.Start();
622 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(clock, q);
Sebastian Jansson73387822020-01-16 11:15:35 +0100623
624 NullSocketServer nullss;
625 Thread q_nullss(&nullss, true);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200626 q_nullss.Start();
627 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(clock, q_nullss);
Sebastian Jansson73387822020-01-16 11:15:35 +0100628}
629
630TEST_F(ThreadQueueTest, DisposeNotLocked) {
631 bool was_locked = true;
632 bool deleted = false;
633 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
634 Dispose(d);
635 Message msg;
Danil Chapovalov207f8532022-08-24 12:19:46 +0200636 ProcessMessages(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100637 EXPECT_TRUE(deleted);
638 EXPECT_FALSE(was_locked);
639}
640
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200641class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100642 public:
643 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
644 ~DeletedMessageHandler() override { *deleted_ = true; }
645 void OnMessage(Message* msg) override {}
646
647 private:
648 bool* deleted_;
649};
650
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200651TEST_F(ThreadQueueTest, DisposeHandlerWithPostedMessagePending) {
Sebastian Jansson73387822020-01-16 11:15:35 +0100652 bool deleted = false;
653 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
654 // First, post a dispose.
655 Dispose(handler);
656 // Now, post a message, which should *not* be returned by Get().
657 Post(RTC_FROM_HERE, handler, 1);
658 Message msg;
Danil Chapovalov207f8532022-08-24 12:19:46 +0200659 ProcessMessages(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100660 EXPECT_TRUE(deleted);
661}
662
663// Ensure that ProcessAllMessageQueues does its essential function; process
664// all messages (both delayed and non delayed) up until the current time, on
665// all registered message queues.
666TEST(ThreadManager, ProcessAllMessageQueues) {
Niels Möller83830f32022-05-20 09:12:57 +0200667 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100668 Event entered_process_all_message_queues(true, false);
669 auto a = Thread::CreateWithSocketServer();
670 auto b = Thread::CreateWithSocketServer();
671 a->Start();
672 b->Start();
673
Niels Möller7a669002022-06-27 09:47:02 +0200674 std::atomic<int> messages_processed(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100675 auto incrementer = [&messages_processed,
676 &entered_process_all_message_queues] {
677 // Wait for event as a means to ensure Increment doesn't occur outside
678 // of ProcessAllMessageQueues. The event is set by a message posted to
679 // the main thread, which is guaranteed to be handled inside
680 // ProcessAllMessageQueues.
681 entered_process_all_message_queues.Wait(Event::kForever);
Niels Möller7a669002022-06-27 09:47:02 +0200682 messages_processed.fetch_add(1);
Sebastian Jansson73387822020-01-16 11:15:35 +0100683 };
684 auto event_signaler = [&entered_process_all_message_queues] {
685 entered_process_all_message_queues.Set();
686 };
687
688 // Post messages (both delayed and non delayed) to both threads.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200689 a->PostTask(incrementer);
690 b->PostTask(incrementer);
691 a->PostDelayedTask(incrementer, TimeDelta::Zero());
692 b->PostDelayedTask(incrementer, TimeDelta::Zero());
693 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100694
695 ThreadManager::ProcessAllMessageQueuesForTesting();
Niels Möller7a669002022-06-27 09:47:02 +0200696 EXPECT_EQ(4, messages_processed.load(std::memory_order_acquire));
Sebastian Jansson73387822020-01-16 11:15:35 +0100697}
698
699// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
700TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
701 auto t = Thread::CreateWithSocketServer();
702 t->Start();
703 t->Quit();
704 ThreadManager::ProcessAllMessageQueuesForTesting();
705}
706
707// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
708// messages.
709TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
Niels Möller83830f32022-05-20 09:12:57 +0200710 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100711 Event entered_process_all_message_queues(true, false);
712 auto t = Thread::CreateWithSocketServer();
713 t->Start();
714
715 auto clearer = [&entered_process_all_message_queues] {
716 // Wait for event as a means to ensure Clear doesn't occur outside of
717 // ProcessAllMessageQueues. The event is set by a message posted to the
718 // main thread, which is guaranteed to be handled inside
719 // ProcessAllMessageQueues.
720 entered_process_all_message_queues.Wait(Event::kForever);
721 rtc::Thread::Current()->Clear(nullptr);
722 };
723 auto event_signaler = [&entered_process_all_message_queues] {
724 entered_process_all_message_queues.Set();
725 };
726
727 // Post messages (both delayed and non delayed) to both threads.
Henrik Boström2deee4b2022-01-20 11:58:05 +0100728 t->PostTask(clearer);
Niels Möller83830f32022-05-20 09:12:57 +0200729 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100730 ThreadManager::ProcessAllMessageQueuesForTesting();
731}
732
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200733class RefCountedHandler : public MessageHandlerAutoCleanup,
734 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100735 public:
736 void OnMessage(Message* msg) override {}
737};
738
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200739class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100740 public:
741 void OnMessage(Message* msg) override {}
742};
743
744TEST(ThreadManager, ClearReentrant) {
745 std::unique_ptr<Thread> t(Thread::Create());
746 EmptyHandler handler;
747 RefCountedHandler* inner_handler(
748 new rtc::RefCountedObject<RefCountedHandler>());
749 // When the empty handler is destroyed, it will clear messages queued for
750 // itself. The message to be cleared itself wraps a MessageHandler object
751 // (RefCountedHandler) so this will cause the message queue to be cleared
752 // again in a re-entrant fashion, which previously triggered a DCHECK.
753 // The inner handler will be removed in a re-entrant fashion from the
754 // message queue of the thread while the outer handler is removed, verifying
755 // that the iterator is not invalidated in "MessageQueue::Clear".
756 t->Post(RTC_FROM_HERE, inner_handler, 0);
757 t->Post(RTC_FROM_HERE, &handler, 0,
758 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
759}
760
Tommi9ebe6d72021-11-16 16:07:34 +0100761class DEPRECATED_AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 public:
763 void IntCallback(int value) {
764 EXPECT_EQ(expected_thread_, Thread::Current());
765 int_value_ = value;
766 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767 void SetExpectedThreadForIntCallback(Thread* thread) {
768 expected_thread_ = thread;
769 }
770
771 protected:
772 enum { kWaitTimeout = 1000 };
Tommi9ebe6d72021-11-16 16:07:34 +0100773 DEPRECATED_AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000774
Niels Möller83830f32022-05-20 09:12:57 +0200775 rtc::AutoThread main_thread_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000777 Thread* expected_thread_;
778};
779
Tommi9ebe6d72021-11-16 16:07:34 +0100780TEST_F(DEPRECATED_AsyncInvokeTest, FireAndForget) {
Niels Möller0694ce72021-05-03 16:03:22 +0200781 DEPRECATED_AsyncInvoker invoker;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000782 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700783 auto thread = Thread::CreateWithSocketServer();
784 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000785 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800786 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700787 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800788 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700789 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000790}
791
Tommi9ebe6d72021-11-16 16:07:34 +0100792TEST_F(DEPRECATED_AsyncInvokeTest, NonCopyableFunctor) {
Niels Möller0694ce72021-05-03 16:03:22 +0200793 DEPRECATED_AsyncInvoker invoker;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700794 // Create and start the thread.
795 auto thread = Thread::CreateWithSocketServer();
796 thread->Start();
797 // Try calling functor.
798 AtomicBool called;
799 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
800 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
801 thread->Stop();
802}
803
Tommi9ebe6d72021-11-16 16:07:34 +0100804TEST_F(DEPRECATED_AsyncInvokeTest, KillInvokerDuringExecute) {
deadbeef162cb532017-02-23 17:10:07 -0800805 // Use these events to get in a state where the functor is in the middle of
806 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
807 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100808 Event functor_started;
809 Event functor_continue;
810 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800811
tommie7251592017-07-14 14:44:46 -0700812 auto thread = Thread::CreateWithSocketServer();
813 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800814 volatile bool invoker_destroyed = false;
815 {
deadbeef3af63b02017-08-08 17:59:47 -0700816 auto functor = [&functor_started, &functor_continue, &functor_finished,
817 &invoker_destroyed] {
818 functor_started.Set();
819 functor_continue.Wait(Event::kForever);
820 rtc::Thread::Current()->SleepMs(kWaitTimeout);
821 EXPECT_FALSE(invoker_destroyed);
822 functor_finished.Set();
823 };
Niels Möller0694ce72021-05-03 16:03:22 +0200824 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700825 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800826 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700827
deadbeef3af63b02017-08-08 17:59:47 -0700828 // Destroy the invoker while the functor is still executing (doing
829 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700830 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800831 }
832
833 // If the destructor DIDN'T wait for the functor to finish executing, it will
834 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
835 // second.
836 invoker_destroyed = true;
837 functor_finished.Wait(Event::kForever);
838}
839
deadbeef3af63b02017-08-08 17:59:47 -0700840// Variant of the above test where the async-invoked task calls AsyncInvoke
Tommi9ebe6d72021-11-16 16:07:34 +0100841// *again*, for the thread on which the invoker is currently being destroyed.
842// This shouldn't deadlock or crash. The second invocation should be ignored.
843TEST_F(DEPRECATED_AsyncInvokeTest,
844 KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100845 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700846 // Flag used to verify that the recursively invoked task never actually runs.
847 bool reentrant_functor_run = false;
848
849 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200850 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700851 thread.Start();
852 {
Niels Möller0694ce72021-05-03 16:03:22 +0200853 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700854 auto reentrant_functor = [&reentrant_functor_run] {
855 reentrant_functor_run = true;
856 };
857 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
858 functor_started.Set();
859 Thread::Current()->SleepMs(kWaitTimeout);
860 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
861 };
Artem Titov96e3b992021-07-26 16:03:14 +0200862 // This queues a task on `thread` to sleep for `kWaitTimeout` then queue a
863 // task on `main`. But this second queued task should never run, since the
deadbeef3af63b02017-08-08 17:59:47 -0700864 // destructor will be entered before it's even invoked.
865 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
866 functor_started.Wait(Event::kForever);
867 }
868 EXPECT_FALSE(reentrant_functor_run);
869}
870
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100871void WaitAndSetEvent(Event* wait_event, Event* set_event) {
872 wait_event->Wait(Event::kForever);
873 set_event->Set();
874}
875
876// A functor that keeps track of the number of copies and moves.
877class LifeCycleFunctor {
878 public:
879 struct Stats {
880 size_t copy_count = 0;
881 size_t move_count = 0;
882 };
883
884 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
885 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
886 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
887
888 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
889 stats_ = other.stats_;
890 event_ = other.event_;
891 ++stats_->copy_count;
892 return *this;
893 }
894
895 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
896 stats_ = other.stats_;
897 event_ = other.event_;
898 ++stats_->move_count;
899 return *this;
900 }
901
902 void operator()() { event_->Set(); }
903
904 private:
905 Stats* stats_;
906 Event* event_;
907};
908
909// A functor that verifies the thread it was destroyed on.
910class DestructionFunctor {
911 public:
912 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
913 : thread_(thread),
914 thread_was_current_(thread_was_current),
915 event_(event) {}
916 ~DestructionFunctor() {
917 // Only signal the event if this was the functor that was invoked to avoid
918 // the event being signaled due to the destruction of temporary/moved
919 // versions of this object.
920 if (was_invoked_) {
921 *thread_was_current_ = thread_->IsCurrent();
922 event_->Set();
923 }
924 }
925
926 void operator()() { was_invoked_ = true; }
927
928 private:
929 Thread* thread_;
930 bool* thread_was_current_;
931 Event* event_;
932 bool was_invoked_ = false;
933};
934
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100935TEST(ThreadPostTaskTest, InvokesWithLambda) {
936 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
937 background_thread->Start();
938
939 Event event;
Henrik Boström595f6882022-01-24 09:57:03 +0100940 background_thread->PostTask([&event] { event.Set(); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100941 event.Wait(Event::kForever);
942}
943
944TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
945 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
946 background_thread->Start();
947
948 LifeCycleFunctor::Stats stats;
949 Event event;
950 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100951 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100952 event.Wait(Event::kForever);
953
954 EXPECT_EQ(1u, stats.copy_count);
955 EXPECT_EQ(0u, stats.move_count);
956}
957
958TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
959 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
960 background_thread->Start();
961
962 LifeCycleFunctor::Stats stats;
963 Event event;
964 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100965 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100966 event.Wait(Event::kForever);
967
968 EXPECT_EQ(0u, stats.copy_count);
969 EXPECT_EQ(1u, stats.move_count);
970}
971
972TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
973 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
974 background_thread->Start();
975
976 LifeCycleFunctor::Stats stats;
977 Event event;
978 LifeCycleFunctor functor(&stats, &event);
979 LifeCycleFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +0100980 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100981 event.Wait(Event::kForever);
982
983 EXPECT_EQ(1u, stats.copy_count);
984 EXPECT_EQ(0u, stats.move_count);
985}
986
987TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
988 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
989 background_thread->Start();
990
991 Event event;
992 bool was_invoked_on_background_thread = false;
993 DestructionFunctor functor(background_thread.get(),
994 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100995 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100996 event.Wait(Event::kForever);
997
998 EXPECT_TRUE(was_invoked_on_background_thread);
999}
1000
1001TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
1002 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1003 background_thread->Start();
1004
1005 Event event;
1006 bool was_invoked_on_background_thread = false;
1007 DestructionFunctor functor(background_thread.get(),
1008 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +01001009 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001010 event.Wait(Event::kForever);
1011
1012 EXPECT_TRUE(was_invoked_on_background_thread);
1013}
1014
1015TEST(ThreadPostTaskTest,
1016 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1017 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1018 background_thread->Start();
1019
1020 Event event;
1021 bool was_invoked_on_background_thread = false;
1022 DestructionFunctor functor(background_thread.get(),
1023 &was_invoked_on_background_thread, &event);
1024 DestructionFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +01001025 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001026 event.Wait(Event::kForever);
1027
1028 EXPECT_TRUE(was_invoked_on_background_thread);
1029}
1030
1031TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1032 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1033 background_thread->Start();
1034
1035 Event event;
1036 bool was_invoked_on_background_thread = false;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001037 Thread* background_thread_ptr = background_thread.get();
Henrik Boström595f6882022-01-24 09:57:03 +01001038 background_thread->PostTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001039 [background_thread_ptr, &was_invoked_on_background_thread, &event] {
1040 was_invoked_on_background_thread = background_thread_ptr->IsCurrent();
1041 event.Set();
1042 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001043 event.Wait(Event::kForever);
1044
1045 EXPECT_TRUE(was_invoked_on_background_thread);
1046}
1047
1048TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1049 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1050 background_thread->Start();
1051
1052 // The first event ensures that SendSingleMessage() is not blocking this
1053 // thread. The second event ensures that the message is processed.
1054 Event event_set_by_test_thread;
1055 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001056 background_thread->PostTask(
Henrik Boström2deee4b2022-01-20 11:58:05 +01001057 [&event_set_by_test_thread, &event_set_by_background_thread] {
1058 WaitAndSetEvent(&event_set_by_test_thread,
1059 &event_set_by_background_thread);
1060 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001061 event_set_by_test_thread.Set();
1062 event_set_by_background_thread.Wait(Event::kForever);
1063}
1064
1065TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1066 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1067 background_thread->Start();
1068
1069 Event first;
1070 Event second;
1071 Event third;
1072 Event fourth;
1073
Henrik Boström595f6882022-01-24 09:57:03 +01001074 background_thread->PostTask(
1075 [&first, &second] { WaitAndSetEvent(&first, &second); });
1076 background_thread->PostTask(
1077 [&second, &third] { WaitAndSetEvent(&second, &third); });
1078 background_thread->PostTask(
1079 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001080
1081 // All tasks have been posted before the first one is unblocked.
1082 first.Set();
1083 // Only if the chain is invoked in posted order will the last event be set.
1084 fourth.Wait(Event::kForever);
1085}
1086
Steve Antonbcc1a762019-12-11 11:21:53 -08001087TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1088 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1089 background_thread->Start();
1090
1091 // The first event ensures that SendSingleMessage() is not blocking this
1092 // thread. The second event ensures that the message is processed.
1093 Event event_set_by_test_thread;
1094 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001095 background_thread->PostDelayedTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001096 [&event_set_by_test_thread, &event_set_by_background_thread] {
1097 WaitAndSetEvent(&event_set_by_test_thread,
1098 &event_set_by_background_thread);
1099 },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001100 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001101 event_set_by_test_thread.Set();
1102 event_set_by_background_thread.Wait(Event::kForever);
1103}
1104
1105TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001106 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001107 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1108 background_thread->Start();
1109
1110 Event first;
1111 Event second;
1112 Event third;
1113 Event fourth;
1114
Henrik Boström595f6882022-01-24 09:57:03 +01001115 background_thread->PostDelayedTask(
1116 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001117 TimeDelta::Millis(11));
Henrik Boström595f6882022-01-24 09:57:03 +01001118 background_thread->PostDelayedTask(
1119 [&first, &second] { WaitAndSetEvent(&first, &second); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001120 TimeDelta::Millis(9));
Henrik Boström595f6882022-01-24 09:57:03 +01001121 background_thread->PostDelayedTask(
1122 [&second, &third] { WaitAndSetEvent(&second, &third); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001123 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001124
1125 // All tasks have been posted before the first one is unblocked.
1126 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001127 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001128 clock.AdvanceTime(TimeDelta::Millis(11));
Markus Handell2cfc1af2022-08-19 08:16:48 +00001129 EXPECT_TRUE(fourth.Wait(TimeDelta::Zero()));
Steve Antonbcc1a762019-12-11 11:21:53 -08001130}
1131
Tommi6866dc72020-05-15 10:11:56 +02001132TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1133 auto current_tq = webrtc::TaskQueueBase::Current();
1134 {
1135 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1136 thread->WrapCurrent();
1137 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1138 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1139 thread->UnwrapCurrent();
1140 }
1141 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1142}
1143
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001144class ThreadFactory : public webrtc::TaskQueueFactory {
1145 public:
1146 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1147 CreateTaskQueue(absl::string_view /* name */,
1148 Priority /*priority*/) const override {
1149 std::unique_ptr<Thread> thread = Thread::Create();
1150 thread->Start();
1151 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1152 thread.release());
1153 }
1154};
1155
Ali Tofigh83db78e2022-08-23 12:57:16 +02001156std::unique_ptr<webrtc::TaskQueueFactory> CreateDefaultThreadFactory(
1157 const webrtc::FieldTrialsView*) {
1158 return std::make_unique<ThreadFactory>();
1159}
1160
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001161using ::webrtc::TaskQueueTest;
1162
1163INSTANTIATE_TEST_SUITE_P(RtcThread,
1164 TaskQueueTest,
Ali Tofigh83db78e2022-08-23 12:57:16 +02001165 ::testing::Values(CreateDefaultThreadFactory));
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001166
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001167} // namespace
1168} // namespace rtc