blob: c88233998b76220649247097aad0f517490124cd [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
Danil Chapovalov912b3b82019-11-22 15:52:40 +010015#include "api/task_queue/task_queue_factory.h"
16#include "api/task_queue/task_queue_test.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020017#include "api/units/time_delta.h"
Steve Anton10542f22019-01-11 09:11:00 -080018#include "rtc_base/async_invoker.h"
19#include "rtc_base/async_udp_socket.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020020#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/event.h"
Danil Chapovalov207f8532022-08-24 12:19:46 +020022#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/gunit.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010024#include "rtc_base/internal/default_socket_server.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "rtc_base/null_socket_server.h"
26#include "rtc_base/physical_socket_server.h"
27#include "rtc_base/socket_address.h"
Markus Handell4ab7dde2020-07-10 13:23:25 +020028#include "rtc_base/synchronization/mutex.h"
Artem Titove41c4332018-07-25 15:04:28 +020029#include "rtc_base/third_party/sigslot/sigslot.h"
Danil Chapovalov207f8532022-08-24 12:19:46 +020030#include "test/gmock.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010031#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032
33#if defined(WEBRTC_WIN)
34#include <comdef.h> // NOLINT
Markus Handell4ab7dde2020-07-10 13:23:25 +020035
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036#endif
37
Mirko Bonadeie10b1632018-12-11 18:43:40 +010038namespace rtc {
39namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040
Danil Chapovalov207f8532022-08-24 12:19:46 +020041using ::testing::ElementsAre;
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020042using ::webrtc::TimeDelta;
Sebastian Jansson73387822020-01-16 11:15:35 +010043
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044// Generates a sequence of numbers (collaboratively).
45class TestGenerator {
46 public:
47 TestGenerator() : last(0), count(0) {}
48
49 int Next(int prev) {
50 int result = prev + last;
51 last = result;
52 count += 1;
53 return result;
54 }
55
56 int last;
57 int count;
58};
59
60struct TestMessage : public MessageData {
61 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062
63 int value;
64};
65
66// Receives on a socket and sends by posting messages.
67class SocketClient : public TestGenerator, public sigslot::has_slots<> {
68 public:
Niels Möllerd0b88792021-08-12 10:32:30 +020069 SocketClient(Socket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +020070 const SocketAddress& addr,
71 Thread* post_thread,
72 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000073 : socket_(AsyncUDPSocket::Create(socket, addr)),
74 post_thread_(post_thread),
75 post_handler_(phandler) {
76 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
77 }
78
Steve Anton9de3aac2017-10-24 10:08:26 -070079 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080
81 SocketAddress address() const { return socket_->GetLocalAddress(); }
82
Yves Gerey665174f2018-06-19 15:03:05 +020083 void OnPacket(AsyncPacketSocket* socket,
84 const char* buf,
85 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010087 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020088 EXPECT_EQ(size, sizeof(uint32_t));
89 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
90 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070092 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
93 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094 }
95
96 private:
97 AsyncUDPSocket* socket_;
98 Thread* post_thread_;
99 MessageHandler* post_handler_;
100};
101
102// Receives messages and sends on a socket.
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200103class MessageClient : public MessageHandlerAutoCleanup, public TestGenerator {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200105 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106
Steve Anton9de3aac2017-10-24 10:08:26 -0700107 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108
Steve Anton9de3aac2017-10-24 10:08:26 -0700109 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
111 int result = Next(msg->value);
112 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
113 delete msg;
114 }
115
116 private:
117 Socket* socket_;
118};
119
deadbeefaea92932017-05-23 12:55:03 -0700120class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121 public:
tommie7251592017-07-14 14:44:46 -0700122 CustomThread()
123 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700124 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000126
Yves Gerey665174f2018-06-19 15:03:05 +0200127 bool WrapCurrent() { return Thread::WrapCurrent(); }
128 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129};
130
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131// A thread that does nothing when it runs and signals an event
132// when it is destroyed.
133class SignalWhenDestroyedThread : public Thread {
134 public:
135 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700136 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
137 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138
Steve Anton9de3aac2017-10-24 10:08:26 -0700139 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 Stop();
141 event_->Set();
142 }
143
Steve Anton9de3aac2017-10-24 10:08:26 -0700144 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 // Do nothing.
146 }
147
148 private:
149 Event* event_;
150};
151
nissed9b75be2015-11-16 00:54:07 -0800152// A bool wrapped in a mutex, to avoid data races. Using a volatile
153// bool should be sufficient for correct code ("eventual consistency"
154// between caches is sufficient), but we can't tell the compiler about
155// that, and then tsan complains about a data race.
156
157// See also discussion at
158// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
159
160// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
161// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700162// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800163// performance critical, use a plain critical section for the time
164// being.
165
166class AtomicBool {
167 public:
168 explicit AtomicBool(bool value = false) : flag_(value) {}
169 AtomicBool& operator=(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200170 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800171 flag_ = value;
172 return *this;
173 }
174 bool get() const {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200175 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800176 return flag_;
177 }
178
179 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200180 mutable webrtc::Mutex mutex_;
nissed9b75be2015-11-16 00:54:07 -0800181 bool flag_;
182};
183
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184// Function objects to test Thread::Invoke.
185struct FunctorA {
186 int operator()() { return 42; }
187};
188class FunctorB {
189 public:
nissed9b75be2015-11-16 00:54:07 -0800190 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200191 void operator()() {
192 if (flag_)
193 *flag_ = true;
194 }
195
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 private:
nissed9b75be2015-11-16 00:54:07 -0800197 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198};
199struct FunctorC {
200 int operator()() {
201 Thread::Current()->ProcessMessages(50);
202 return 24;
203 }
204};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700205struct FunctorD {
206 public:
207 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
208 FunctorD(FunctorD&&) = default;
Byoungchan Lee14af7622022-01-12 05:24:58 +0900209
210 FunctorD(const FunctorD&) = delete;
211 FunctorD& operator=(const FunctorD&) = delete;
212
Cameron Pickettd132ce12018-03-12 16:07:37 -0700213 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200214 void operator()() {
215 if (flag_)
216 *flag_ = true;
217 }
218
Cameron Pickettd132ce12018-03-12 16:07:37 -0700219 private:
220 AtomicBool* flag_;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700221};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222
223// See: https://code.google.com/p/webrtc/issues/detail?id=2409
224TEST(ThreadTest, DISABLED_Main) {
225 const SocketAddress addr("127.0.0.1", 0);
226
227 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700228 auto th1 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200229 Socket* socket = th1->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700230 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231
232 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700233 auto th2 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200234 Socket* asocket =
235 th2->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700236 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238 socket->Connect(sock_client.address());
239
tommie7251592017-07-14 14:44:46 -0700240 th1->Start();
241 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242
243 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700244 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245
246 // Give the clients a little while to run.
247 // Messages will be processed at 100, 300, 500, 700, 900.
248 Thread* th_main = Thread::Current();
249 th_main->ProcessMessages(1000);
250
251 // Stop the sending client. Give the receiver a bit longer to run, in case
252 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700253 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700255 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
257 // Make sure the results were correct
258 EXPECT_EQ(5, msg_client.count);
259 EXPECT_EQ(34, msg_client.last);
260 EXPECT_EQ(5, sock_client.count);
261 EXPECT_EQ(55, sock_client.last);
262}
263
Tommife041642021-04-07 10:08:28 +0200264TEST(ThreadTest, CountBlockingCalls) {
Niels Möller83830f32022-05-20 09:12:57 +0200265 rtc::AutoThread current;
266
Tommife041642021-04-07 10:08:28 +0200267 // When the test runs, this will print out:
268 // (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
269 RTC_LOG_THREAD_BLOCK_COUNT();
270#if RTC_DCHECK_IS_ON
Tommife041642021-04-07 10:08:28 +0200271 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
272 [&](uint32_t actual_block, uint32_t could_block) {
273 EXPECT_EQ(1u, actual_block);
274 EXPECT_EQ(1u, could_block);
275 });
276
277 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
278 EXPECT_EQ(0u, blocked_calls.GetCouldBeBlockingCallCount());
279 EXPECT_EQ(0u, blocked_calls.GetTotalBlockedCallCount());
280
281 // Test invoking on the current thread. This should not count as an 'actual'
282 // invoke, but should still count as an invoke that could block since we
283 // that the call to Invoke serves a purpose in some configurations (and should
284 // not be used a general way to call methods on the same thread).
Niels Möller83830f32022-05-20 09:12:57 +0200285 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tommife041642021-04-07 10:08:28 +0200286 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
287 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
288 EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
289
290 // Create a new thread to invoke on.
291 auto thread = Thread::CreateWithSocketServer();
292 thread->Start();
293 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, []() { return 42; }));
294 EXPECT_EQ(1u, blocked_calls.GetBlockingCallCount());
295 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
296 EXPECT_EQ(2u, blocked_calls.GetTotalBlockedCallCount());
297 thread->Stop();
298 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2);
299#else
300 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
301 RTC_LOG(LS_INFO) << "Test not active in this config";
302#endif
303}
304
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200305#if RTC_DCHECK_IS_ON
306TEST(ThreadTest, CountBlockingCallsOneCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200307 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200308 bool was_called_back = false;
309 {
310 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
311 [&](uint32_t actual_block, uint32_t could_block) {
312 was_called_back = true;
313 });
Niels Möller83830f32022-05-20 09:12:57 +0200314 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200315 }
316 EXPECT_TRUE(was_called_back);
317}
318
319TEST(ThreadTest, CountBlockingCallsSkipCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200320 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200321 bool was_called_back = false;
322 {
323 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
324 [&](uint32_t actual_block, uint32_t could_block) {
325 was_called_back = true;
326 });
327 // Changed `blocked_calls` to not issue the callback if there are 1 or
328 // fewer blocking calls (i.e. we set the minimum required number to 2).
329 blocked_calls.set_minimum_call_count_for_callback(2);
Niels Möller83830f32022-05-20 09:12:57 +0200330 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200331 }
332 // We should not have gotten a call back.
333 EXPECT_FALSE(was_called_back);
334}
335#endif
336
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337// Test that setting thread names doesn't cause a malfunction.
338// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000339TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 // Default name
tommie7251592017-07-14 14:44:46 -0700341 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342 EXPECT_TRUE(thread->Start());
343 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700345 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800346 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347 EXPECT_TRUE(thread->Start());
348 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349 // Really long name
tommie7251592017-07-14 14:44:46 -0700350 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
352 EXPECT_TRUE(thread->Start());
353 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354}
355
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000356TEST(ThreadTest, Wrap) {
357 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200358 ThreadManager::Instance()->SetCurrentThread(nullptr);
359
360 {
361 CustomThread cthread;
362 EXPECT_TRUE(cthread.WrapCurrent());
363 EXPECT_EQ(&cthread, Thread::Current());
364 EXPECT_TRUE(cthread.RunningForTest());
365 EXPECT_FALSE(cthread.IsOwned());
366 cthread.UnwrapCurrent();
367 EXPECT_FALSE(cthread.RunningForTest());
368 }
369 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370}
371
Mirko Bonadei481e3452021-07-30 13:57:25 +0200372#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200373TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
Niels Möller83830f32022-05-20 09:12:57 +0200374 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200375 // Create and start the thread.
376 auto thread1 = Thread::CreateWithSocketServer();
377 auto thread2 = Thread::CreateWithSocketServer();
378
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200379 thread1->PostTask(
380 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200381 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200382}
383
384TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
Niels Möller83830f32022-05-20 09:12:57 +0200385 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200386 // Create and start the thread.
387 auto thread1 = Thread::CreateWithSocketServer();
388 auto thread2 = Thread::CreateWithSocketServer();
389 auto thread3 = Thread::CreateWithSocketServer();
390 auto thread4 = Thread::CreateWithSocketServer();
391
392 thread1->AllowInvokesToThread(thread2.get());
393 thread1->AllowInvokesToThread(thread3.get());
394
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200395 thread1->PostTask([&]() {
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200396 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
397 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
398 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200399 });
Niels Möller83830f32022-05-20 09:12:57 +0200400 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200401}
402
403TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
Niels Möller83830f32022-05-20 09:12:57 +0200404 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200405 // Create and start the thread.
406 auto thread1 = Thread::CreateWithSocketServer();
407 auto thread2 = Thread::CreateWithSocketServer();
408
409 thread1->DisallowAllInvokes();
410
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200411 thread1->PostTask(
412 [&]() { EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200413 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200414}
Mirko Bonadei481e3452021-07-30 13:57:25 +0200415#endif // (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200416
417TEST(ThreadTest, InvokesAllowedByDefault) {
Niels Möller83830f32022-05-20 09:12:57 +0200418 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200419 // Create and start the thread.
420 auto thread1 = Thread::CreateWithSocketServer();
421 auto thread2 = Thread::CreateWithSocketServer();
422
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200423 thread1->PostTask(
424 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200425 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200426}
427
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000428TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700430 auto thread = Thread::CreateWithSocketServer();
431 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000432 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700433 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800434 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700436 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800437 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000438 // Try calling bare functions.
439 struct LocalFuncs {
440 static int Func1() { return 999; }
441 static void Func2() {}
442 };
tommie7251592017-07-14 14:44:46 -0700443 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
444 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000445}
446
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000447// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100448// not deadlock but crash.
449#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
450TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200451 GTEST_FLAG_SET(death_test_style, "threadsafe");
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000452 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100453 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700454 auto other_thread = Thread::CreateWithSocketServer();
455 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100456 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
457 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
458 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000459}
460
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100461TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200462 GTEST_FLAG_SET(death_test_style, "threadsafe");
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100463 AutoThread thread;
464 Thread* first = Thread::Current();
465
466 auto second = Thread::Create();
467 second->Start();
468 auto third = Thread::Create();
469 third->Start();
470
471 second->Invoke<void>(RTC_FROM_HERE, [&] {
472 third->Invoke<void>(RTC_FROM_HERE, [&] {
473 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
474 });
475 });
476}
477
478#endif
479
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000480// Verifies that if thread A invokes a call on thread B and thread C is trying
481// to invoke A at the same time, thread A does not handle C's invoke while
482// invoking B.
483TEST(ThreadTest, ThreeThreadsInvoke) {
484 AutoThread thread;
485 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700486 auto thread_b = Thread::CreateWithSocketServer();
487 auto thread_c = Thread::CreateWithSocketServer();
488 thread_b->Start();
489 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000490
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000491 class LockedBool {
492 public:
493 explicit LockedBool(bool value) : value_(value) {}
494
495 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200496 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000497 value_ = value;
498 }
499
500 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200501 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000502 return value_;
503 }
504
505 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200506 webrtc::Mutex mutex_;
507 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000508 };
509
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000510 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000511 static void Set(LockedBool* out) { out->Set(true); }
512 static void InvokeSet(Thread* thread, LockedBool* out) {
Niels Möller1a29a5d2021-01-18 11:35:23 +0100513 thread->Invoke<void>(RTC_FROM_HERE, [out] { Set(out); });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000514 }
515
Artem Titov96e3b992021-07-26 16:03:14 +0200516 // Set `out` true and call InvokeSet on `thread`.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000517 static void SetAndInvokeSet(LockedBool* out,
518 Thread* thread,
519 LockedBool* out_inner) {
520 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000521 InvokeSet(thread, out_inner);
522 }
523
Artem Titov96e3b992021-07-26 16:03:14 +0200524 // Asynchronously invoke SetAndInvokeSet on `thread1` and wait until
525 // `thread1` starts the call.
Niels Möller0694ce72021-05-03 16:03:22 +0200526 static void AsyncInvokeSetAndWait(DEPRECATED_AsyncInvoker* invoker,
deadbeef162cb532017-02-23 17:10:07 -0800527 Thread* thread1,
528 Thread* thread2,
529 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000530 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000531
deadbeef162cb532017-02-23 17:10:07 -0800532 invoker->AsyncInvoke<void>(
Niels Möller1a29a5d2021-01-18 11:35:23 +0100533 RTC_FROM_HERE, thread1, [&async_invoked, thread2, out] {
534 SetAndInvokeSet(&async_invoked, thread2, out);
535 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000536
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000537 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000538 }
539 };
540
Niels Möller0694ce72021-05-03 16:03:22 +0200541 DEPRECATED_AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000542 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000543
544 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
545 // Thread B returns when C receives the call and C should be blocked until A
546 // starts to process messages.
Niels Möller1a29a5d2021-01-18 11:35:23 +0100547 Thread* thread_c_ptr = thread_c.get();
548 thread_b->Invoke<void>(
549 RTC_FROM_HERE, [&invoker, thread_c_ptr, thread_a, &thread_a_called] {
550 LocalFuncs::AsyncInvokeSetAndWait(&invoker, thread_c_ptr, thread_a,
551 &thread_a_called);
552 });
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000553 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000554
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000555 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000556}
557
Sebastian Jansson73387822020-01-16 11:15:35 +0100558class ThreadQueueTest : public ::testing::Test, public Thread {
559 public:
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200560 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {
561 RTC_DCHECK(Thread::Current() == nullptr);
562 ThreadManager::Instance()->SetCurrentThread(this);
563 }
564 ~ThreadQueueTest() { ThreadManager::Instance()->SetCurrentThread(nullptr); }
Sebastian Jansson73387822020-01-16 11:15:35 +0100565 bool IsLocked_Worker() {
566 if (!CritForTest()->TryEnter()) {
567 return true;
568 }
569 CritForTest()->Leave();
570 return false;
571 }
572 bool IsLocked() {
573 // We have to do this on a worker thread, or else the TryEnter will
574 // succeed, since our critical sections are reentrant.
575 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
576 worker->Start();
Niels Möller1a29a5d2021-01-18 11:35:23 +0100577 return worker->Invoke<bool>(RTC_FROM_HERE,
578 [this] { return IsLocked_Worker(); });
Sebastian Jansson73387822020-01-16 11:15:35 +0100579 }
580};
581
582struct DeletedLockChecker {
583 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
584 : test(test), was_locked(was_locked), deleted(deleted) {}
585 ~DeletedLockChecker() {
586 *deleted = true;
587 *was_locked = test->IsLocked();
588 }
589 ThreadQueueTest* test;
590 bool* was_locked;
591 bool* deleted;
592};
593
Danil Chapovalov207f8532022-08-24 12:19:46 +0200594static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(
595 FakeClock& clock,
596 Thread& q) {
597 std::vector<int> run_order;
598
599 Event done;
Sebastian Jansson73387822020-01-16 11:15:35 +0100600 int64_t now = TimeMillis();
Danil Chapovalov207f8532022-08-24 12:19:46 +0200601 q.PostDelayedTask([&] { run_order.push_back(3); }, TimeDelta::Millis(3));
602 q.PostDelayedTask([&] { run_order.push_back(0); }, TimeDelta::Millis(1));
603 q.PostDelayedTask([&] { run_order.push_back(1); }, TimeDelta::Millis(2));
604 q.PostDelayedTask([&] { run_order.push_back(4); }, TimeDelta::Millis(3));
605 q.PostDelayedTask([&] { run_order.push_back(2); }, TimeDelta::Millis(2));
606 q.PostDelayedTask([&] { done.Set(); }, TimeDelta::Millis(4));
607 // Validate time was frozen while tasks were posted.
608 RTC_DCHECK_EQ(TimeMillis(), now);
Sebastian Jansson73387822020-01-16 11:15:35 +0100609
Danil Chapovalov207f8532022-08-24 12:19:46 +0200610 // Change time to make all tasks ready to run and wait for them.
611 clock.AdvanceTime(TimeDelta::Millis(4));
612 ASSERT_TRUE(done.Wait(TimeDelta::Seconds(1)));
Sebastian Jansson73387822020-01-16 11:15:35 +0100613
Danil Chapovalov207f8532022-08-24 12:19:46 +0200614 EXPECT_THAT(run_order, ElementsAre(0, 1, 2, 3, 4));
Sebastian Jansson73387822020-01-16 11:15:35 +0100615}
616
617TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Danil Chapovalov207f8532022-08-24 12:19:46 +0200618 ScopedBaseFakeClock clock;
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100619 Thread q(CreateDefaultSocketServer(), true);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200620 q.Start();
621 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(clock, q);
Sebastian Jansson73387822020-01-16 11:15:35 +0100622
623 NullSocketServer nullss;
624 Thread q_nullss(&nullss, true);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200625 q_nullss.Start();
626 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(clock, q_nullss);
Sebastian Jansson73387822020-01-16 11:15:35 +0100627}
628
629TEST_F(ThreadQueueTest, DisposeNotLocked) {
630 bool was_locked = true;
631 bool deleted = false;
632 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
633 Dispose(d);
634 Message msg;
Danil Chapovalov207f8532022-08-24 12:19:46 +0200635 ProcessMessages(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100636 EXPECT_TRUE(deleted);
637 EXPECT_FALSE(was_locked);
638}
639
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200640class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100641 public:
642 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
643 ~DeletedMessageHandler() override { *deleted_ = true; }
644 void OnMessage(Message* msg) override {}
645
646 private:
647 bool* deleted_;
648};
649
Danil Chapovalov0bd16652022-08-24 18:35:45 +0200650TEST_F(ThreadQueueTest, DisposeHandlerWithPostedMessagePending) {
Sebastian Jansson73387822020-01-16 11:15:35 +0100651 bool deleted = false;
652 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
653 // First, post a dispose.
654 Dispose(handler);
655 // Now, post a message, which should *not* be returned by Get().
656 Post(RTC_FROM_HERE, handler, 1);
657 Message msg;
Danil Chapovalov207f8532022-08-24 12:19:46 +0200658 ProcessMessages(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100659 EXPECT_TRUE(deleted);
660}
661
662// Ensure that ProcessAllMessageQueues does its essential function; process
663// all messages (both delayed and non delayed) up until the current time, on
664// all registered message queues.
665TEST(ThreadManager, ProcessAllMessageQueues) {
Niels Möller83830f32022-05-20 09:12:57 +0200666 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100667 Event entered_process_all_message_queues(true, false);
668 auto a = Thread::CreateWithSocketServer();
669 auto b = Thread::CreateWithSocketServer();
670 a->Start();
671 b->Start();
672
Niels Möller7a669002022-06-27 09:47:02 +0200673 std::atomic<int> messages_processed(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100674 auto incrementer = [&messages_processed,
675 &entered_process_all_message_queues] {
676 // Wait for event as a means to ensure Increment doesn't occur outside
677 // of ProcessAllMessageQueues. The event is set by a message posted to
678 // the main thread, which is guaranteed to be handled inside
679 // ProcessAllMessageQueues.
680 entered_process_all_message_queues.Wait(Event::kForever);
Niels Möller7a669002022-06-27 09:47:02 +0200681 messages_processed.fetch_add(1);
Sebastian Jansson73387822020-01-16 11:15:35 +0100682 };
683 auto event_signaler = [&entered_process_all_message_queues] {
684 entered_process_all_message_queues.Set();
685 };
686
687 // Post messages (both delayed and non delayed) to both threads.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200688 a->PostTask(incrementer);
689 b->PostTask(incrementer);
690 a->PostDelayedTask(incrementer, TimeDelta::Zero());
691 b->PostDelayedTask(incrementer, TimeDelta::Zero());
692 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100693
694 ThreadManager::ProcessAllMessageQueuesForTesting();
Niels Möller7a669002022-06-27 09:47:02 +0200695 EXPECT_EQ(4, messages_processed.load(std::memory_order_acquire));
Sebastian Jansson73387822020-01-16 11:15:35 +0100696}
697
698// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
699TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
700 auto t = Thread::CreateWithSocketServer();
701 t->Start();
702 t->Quit();
703 ThreadManager::ProcessAllMessageQueuesForTesting();
704}
705
706// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
707// messages.
708TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
Niels Möller83830f32022-05-20 09:12:57 +0200709 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100710 Event entered_process_all_message_queues(true, false);
711 auto t = Thread::CreateWithSocketServer();
712 t->Start();
713
714 auto clearer = [&entered_process_all_message_queues] {
715 // Wait for event as a means to ensure Clear doesn't occur outside of
716 // ProcessAllMessageQueues. The event is set by a message posted to the
717 // main thread, which is guaranteed to be handled inside
718 // ProcessAllMessageQueues.
719 entered_process_all_message_queues.Wait(Event::kForever);
720 rtc::Thread::Current()->Clear(nullptr);
721 };
722 auto event_signaler = [&entered_process_all_message_queues] {
723 entered_process_all_message_queues.Set();
724 };
725
726 // Post messages (both delayed and non delayed) to both threads.
Henrik Boström2deee4b2022-01-20 11:58:05 +0100727 t->PostTask(clearer);
Niels Möller83830f32022-05-20 09:12:57 +0200728 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100729 ThreadManager::ProcessAllMessageQueuesForTesting();
730}
731
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200732class RefCountedHandler : public MessageHandlerAutoCleanup,
733 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100734 public:
735 void OnMessage(Message* msg) override {}
736};
737
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200738class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100739 public:
740 void OnMessage(Message* msg) override {}
741};
742
743TEST(ThreadManager, ClearReentrant) {
744 std::unique_ptr<Thread> t(Thread::Create());
745 EmptyHandler handler;
746 RefCountedHandler* inner_handler(
747 new rtc::RefCountedObject<RefCountedHandler>());
748 // When the empty handler is destroyed, it will clear messages queued for
749 // itself. The message to be cleared itself wraps a MessageHandler object
750 // (RefCountedHandler) so this will cause the message queue to be cleared
751 // again in a re-entrant fashion, which previously triggered a DCHECK.
752 // The inner handler will be removed in a re-entrant fashion from the
753 // message queue of the thread while the outer handler is removed, verifying
754 // that the iterator is not invalidated in "MessageQueue::Clear".
755 t->Post(RTC_FROM_HERE, inner_handler, 0);
756 t->Post(RTC_FROM_HERE, &handler, 0,
757 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
758}
759
Tommi9ebe6d72021-11-16 16:07:34 +0100760class DEPRECATED_AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761 public:
762 void IntCallback(int value) {
763 EXPECT_EQ(expected_thread_, Thread::Current());
764 int_value_ = value;
765 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000766 void SetExpectedThreadForIntCallback(Thread* thread) {
767 expected_thread_ = thread;
768 }
769
770 protected:
771 enum { kWaitTimeout = 1000 };
Tommi9ebe6d72021-11-16 16:07:34 +0100772 DEPRECATED_AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000773
Niels Möller83830f32022-05-20 09:12:57 +0200774 rtc::AutoThread main_thread_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000775 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776 Thread* expected_thread_;
777};
778
Tommi9ebe6d72021-11-16 16:07:34 +0100779TEST_F(DEPRECATED_AsyncInvokeTest, FireAndForget) {
Niels Möller0694ce72021-05-03 16:03:22 +0200780 DEPRECATED_AsyncInvoker invoker;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700782 auto thread = Thread::CreateWithSocketServer();
783 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000784 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800785 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700786 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800787 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700788 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000789}
790
Tommi9ebe6d72021-11-16 16:07:34 +0100791TEST_F(DEPRECATED_AsyncInvokeTest, NonCopyableFunctor) {
Niels Möller0694ce72021-05-03 16:03:22 +0200792 DEPRECATED_AsyncInvoker invoker;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700793 // Create and start the thread.
794 auto thread = Thread::CreateWithSocketServer();
795 thread->Start();
796 // Try calling functor.
797 AtomicBool called;
798 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
799 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
800 thread->Stop();
801}
802
Tommi9ebe6d72021-11-16 16:07:34 +0100803TEST_F(DEPRECATED_AsyncInvokeTest, KillInvokerDuringExecute) {
deadbeef162cb532017-02-23 17:10:07 -0800804 // Use these events to get in a state where the functor is in the middle of
805 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
806 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100807 Event functor_started;
808 Event functor_continue;
809 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800810
tommie7251592017-07-14 14:44:46 -0700811 auto thread = Thread::CreateWithSocketServer();
812 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800813 volatile bool invoker_destroyed = false;
814 {
deadbeef3af63b02017-08-08 17:59:47 -0700815 auto functor = [&functor_started, &functor_continue, &functor_finished,
816 &invoker_destroyed] {
817 functor_started.Set();
818 functor_continue.Wait(Event::kForever);
819 rtc::Thread::Current()->SleepMs(kWaitTimeout);
820 EXPECT_FALSE(invoker_destroyed);
821 functor_finished.Set();
822 };
Niels Möller0694ce72021-05-03 16:03:22 +0200823 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700824 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800825 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700826
deadbeef3af63b02017-08-08 17:59:47 -0700827 // Destroy the invoker while the functor is still executing (doing
828 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700829 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800830 }
831
832 // If the destructor DIDN'T wait for the functor to finish executing, it will
833 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
834 // second.
835 invoker_destroyed = true;
836 functor_finished.Wait(Event::kForever);
837}
838
deadbeef3af63b02017-08-08 17:59:47 -0700839// Variant of the above test where the async-invoked task calls AsyncInvoke
Tommi9ebe6d72021-11-16 16:07:34 +0100840// *again*, for the thread on which the invoker is currently being destroyed.
841// This shouldn't deadlock or crash. The second invocation should be ignored.
842TEST_F(DEPRECATED_AsyncInvokeTest,
843 KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100844 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700845 // Flag used to verify that the recursively invoked task never actually runs.
846 bool reentrant_functor_run = false;
847
848 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200849 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700850 thread.Start();
851 {
Niels Möller0694ce72021-05-03 16:03:22 +0200852 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700853 auto reentrant_functor = [&reentrant_functor_run] {
854 reentrant_functor_run = true;
855 };
856 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
857 functor_started.Set();
858 Thread::Current()->SleepMs(kWaitTimeout);
859 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
860 };
Artem Titov96e3b992021-07-26 16:03:14 +0200861 // This queues a task on `thread` to sleep for `kWaitTimeout` then queue a
862 // task on `main`. But this second queued task should never run, since the
deadbeef3af63b02017-08-08 17:59:47 -0700863 // destructor will be entered before it's even invoked.
864 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
865 functor_started.Wait(Event::kForever);
866 }
867 EXPECT_FALSE(reentrant_functor_run);
868}
869
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100870void WaitAndSetEvent(Event* wait_event, Event* set_event) {
871 wait_event->Wait(Event::kForever);
872 set_event->Set();
873}
874
875// A functor that keeps track of the number of copies and moves.
876class LifeCycleFunctor {
877 public:
878 struct Stats {
879 size_t copy_count = 0;
880 size_t move_count = 0;
881 };
882
883 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
884 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
885 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
886
887 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
888 stats_ = other.stats_;
889 event_ = other.event_;
890 ++stats_->copy_count;
891 return *this;
892 }
893
894 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
895 stats_ = other.stats_;
896 event_ = other.event_;
897 ++stats_->move_count;
898 return *this;
899 }
900
901 void operator()() { event_->Set(); }
902
903 private:
904 Stats* stats_;
905 Event* event_;
906};
907
908// A functor that verifies the thread it was destroyed on.
909class DestructionFunctor {
910 public:
911 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
912 : thread_(thread),
913 thread_was_current_(thread_was_current),
914 event_(event) {}
915 ~DestructionFunctor() {
916 // Only signal the event if this was the functor that was invoked to avoid
917 // the event being signaled due to the destruction of temporary/moved
918 // versions of this object.
919 if (was_invoked_) {
920 *thread_was_current_ = thread_->IsCurrent();
921 event_->Set();
922 }
923 }
924
925 void operator()() { was_invoked_ = true; }
926
927 private:
928 Thread* thread_;
929 bool* thread_was_current_;
930 Event* event_;
931 bool was_invoked_ = false;
932};
933
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100934TEST(ThreadPostTaskTest, InvokesWithLambda) {
935 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
936 background_thread->Start();
937
938 Event event;
Henrik Boström595f6882022-01-24 09:57:03 +0100939 background_thread->PostTask([&event] { event.Set(); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100940 event.Wait(Event::kForever);
941}
942
943TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
944 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
945 background_thread->Start();
946
947 LifeCycleFunctor::Stats stats;
948 Event event;
949 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100950 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100951 event.Wait(Event::kForever);
952
953 EXPECT_EQ(1u, stats.copy_count);
954 EXPECT_EQ(0u, stats.move_count);
955}
956
957TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
958 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
959 background_thread->Start();
960
961 LifeCycleFunctor::Stats stats;
962 Event event;
963 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100964 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100965 event.Wait(Event::kForever);
966
967 EXPECT_EQ(0u, stats.copy_count);
968 EXPECT_EQ(1u, stats.move_count);
969}
970
971TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
972 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
973 background_thread->Start();
974
975 LifeCycleFunctor::Stats stats;
976 Event event;
977 LifeCycleFunctor functor(&stats, &event);
978 LifeCycleFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +0100979 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100980 event.Wait(Event::kForever);
981
982 EXPECT_EQ(1u, stats.copy_count);
983 EXPECT_EQ(0u, stats.move_count);
984}
985
986TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
987 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
988 background_thread->Start();
989
990 Event event;
991 bool was_invoked_on_background_thread = false;
992 DestructionFunctor functor(background_thread.get(),
993 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100994 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100995 event.Wait(Event::kForever);
996
997 EXPECT_TRUE(was_invoked_on_background_thread);
998}
999
1000TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
1001 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1002 background_thread->Start();
1003
1004 Event event;
1005 bool was_invoked_on_background_thread = false;
1006 DestructionFunctor functor(background_thread.get(),
1007 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +01001008 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001009 event.Wait(Event::kForever);
1010
1011 EXPECT_TRUE(was_invoked_on_background_thread);
1012}
1013
1014TEST(ThreadPostTaskTest,
1015 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1016 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1017 background_thread->Start();
1018
1019 Event event;
1020 bool was_invoked_on_background_thread = false;
1021 DestructionFunctor functor(background_thread.get(),
1022 &was_invoked_on_background_thread, &event);
1023 DestructionFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +01001024 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001025 event.Wait(Event::kForever);
1026
1027 EXPECT_TRUE(was_invoked_on_background_thread);
1028}
1029
1030TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1031 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1032 background_thread->Start();
1033
1034 Event event;
1035 bool was_invoked_on_background_thread = false;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001036 Thread* background_thread_ptr = background_thread.get();
Henrik Boström595f6882022-01-24 09:57:03 +01001037 background_thread->PostTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001038 [background_thread_ptr, &was_invoked_on_background_thread, &event] {
1039 was_invoked_on_background_thread = background_thread_ptr->IsCurrent();
1040 event.Set();
1041 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001042 event.Wait(Event::kForever);
1043
1044 EXPECT_TRUE(was_invoked_on_background_thread);
1045}
1046
1047TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1048 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1049 background_thread->Start();
1050
1051 // The first event ensures that SendSingleMessage() is not blocking this
1052 // thread. The second event ensures that the message is processed.
1053 Event event_set_by_test_thread;
1054 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001055 background_thread->PostTask(
Henrik Boström2deee4b2022-01-20 11:58:05 +01001056 [&event_set_by_test_thread, &event_set_by_background_thread] {
1057 WaitAndSetEvent(&event_set_by_test_thread,
1058 &event_set_by_background_thread);
1059 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001060 event_set_by_test_thread.Set();
1061 event_set_by_background_thread.Wait(Event::kForever);
1062}
1063
1064TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1065 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1066 background_thread->Start();
1067
1068 Event first;
1069 Event second;
1070 Event third;
1071 Event fourth;
1072
Henrik Boström595f6882022-01-24 09:57:03 +01001073 background_thread->PostTask(
1074 [&first, &second] { WaitAndSetEvent(&first, &second); });
1075 background_thread->PostTask(
1076 [&second, &third] { WaitAndSetEvent(&second, &third); });
1077 background_thread->PostTask(
1078 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001079
1080 // All tasks have been posted before the first one is unblocked.
1081 first.Set();
1082 // Only if the chain is invoked in posted order will the last event be set.
1083 fourth.Wait(Event::kForever);
1084}
1085
Steve Antonbcc1a762019-12-11 11:21:53 -08001086TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1087 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1088 background_thread->Start();
1089
1090 // The first event ensures that SendSingleMessage() is not blocking this
1091 // thread. The second event ensures that the message is processed.
1092 Event event_set_by_test_thread;
1093 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001094 background_thread->PostDelayedTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001095 [&event_set_by_test_thread, &event_set_by_background_thread] {
1096 WaitAndSetEvent(&event_set_by_test_thread,
1097 &event_set_by_background_thread);
1098 },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001099 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001100 event_set_by_test_thread.Set();
1101 event_set_by_background_thread.Wait(Event::kForever);
1102}
1103
1104TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001105 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001106 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1107 background_thread->Start();
1108
1109 Event first;
1110 Event second;
1111 Event third;
1112 Event fourth;
1113
Henrik Boström595f6882022-01-24 09:57:03 +01001114 background_thread->PostDelayedTask(
1115 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001116 TimeDelta::Millis(11));
Henrik Boström595f6882022-01-24 09:57:03 +01001117 background_thread->PostDelayedTask(
1118 [&first, &second] { WaitAndSetEvent(&first, &second); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001119 TimeDelta::Millis(9));
Henrik Boström595f6882022-01-24 09:57:03 +01001120 background_thread->PostDelayedTask(
1121 [&second, &third] { WaitAndSetEvent(&second, &third); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001122 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001123
1124 // All tasks have been posted before the first one is unblocked.
1125 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001126 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001127 clock.AdvanceTime(TimeDelta::Millis(11));
Markus Handell2cfc1af2022-08-19 08:16:48 +00001128 EXPECT_TRUE(fourth.Wait(TimeDelta::Zero()));
Steve Antonbcc1a762019-12-11 11:21:53 -08001129}
1130
Tommi6866dc72020-05-15 10:11:56 +02001131TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1132 auto current_tq = webrtc::TaskQueueBase::Current();
1133 {
1134 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1135 thread->WrapCurrent();
1136 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1137 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1138 thread->UnwrapCurrent();
1139 }
1140 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1141}
1142
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001143class ThreadFactory : public webrtc::TaskQueueFactory {
1144 public:
1145 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1146 CreateTaskQueue(absl::string_view /* name */,
1147 Priority /*priority*/) const override {
1148 std::unique_ptr<Thread> thread = Thread::Create();
1149 thread->Start();
1150 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1151 thread.release());
1152 }
1153};
1154
1155using ::webrtc::TaskQueueTest;
1156
1157INSTANTIATE_TEST_SUITE_P(RtcThread,
1158 TaskQueueTest,
Ali Tofighe7e3d592022-08-25 10:09:48 +00001159 ::testing::Values(std::make_unique<ThreadFactory>));
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001160
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001161} // namespace
1162} // namespace rtc