blob: 75f13d4016dcaf4ea29fc9e9f8d0c722bd50c91e [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"
22#include "rtc_base/gunit.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010023#include "rtc_base/internal/default_socket_server.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/null_socket_server.h"
25#include "rtc_base/physical_socket_server.h"
26#include "rtc_base/socket_address.h"
Markus Handell4ab7dde2020-07-10 13:23:25 +020027#include "rtc_base/synchronization/mutex.h"
Artem Titove41c4332018-07-25 15:04:28 +020028#include "rtc_base/third_party/sigslot/sigslot.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010029#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
31#if defined(WEBRTC_WIN)
32#include <comdef.h> // NOLINT
Markus Handell4ab7dde2020-07-10 13:23:25 +020033
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034#endif
35
Mirko Bonadeie10b1632018-12-11 18:43:40 +010036namespace rtc {
37namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020039using ::webrtc::TimeDelta;
Sebastian Jansson73387822020-01-16 11:15:35 +010040
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041// Generates a sequence of numbers (collaboratively).
42class TestGenerator {
43 public:
44 TestGenerator() : last(0), count(0) {}
45
46 int Next(int prev) {
47 int result = prev + last;
48 last = result;
49 count += 1;
50 return result;
51 }
52
53 int last;
54 int count;
55};
56
57struct TestMessage : public MessageData {
58 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059
60 int value;
61};
62
63// Receives on a socket and sends by posting messages.
64class SocketClient : public TestGenerator, public sigslot::has_slots<> {
65 public:
Niels Möllerd0b88792021-08-12 10:32:30 +020066 SocketClient(Socket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +020067 const SocketAddress& addr,
68 Thread* post_thread,
69 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070 : socket_(AsyncUDPSocket::Create(socket, addr)),
71 post_thread_(post_thread),
72 post_handler_(phandler) {
73 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
74 }
75
Steve Anton9de3aac2017-10-24 10:08:26 -070076 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077
78 SocketAddress address() const { return socket_->GetLocalAddress(); }
79
Yves Gerey665174f2018-06-19 15:03:05 +020080 void OnPacket(AsyncPacketSocket* socket,
81 const char* buf,
82 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010084 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020085 EXPECT_EQ(size, sizeof(uint32_t));
86 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
87 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070089 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
90 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091 }
92
93 private:
94 AsyncUDPSocket* socket_;
95 Thread* post_thread_;
96 MessageHandler* post_handler_;
97};
98
99// Receives messages and sends on a socket.
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200100class MessageClient : public MessageHandlerAutoCleanup, public TestGenerator {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000101 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200102 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103
Steve Anton9de3aac2017-10-24 10:08:26 -0700104 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105
Steve Anton9de3aac2017-10-24 10:08:26 -0700106 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
108 int result = Next(msg->value);
109 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
110 delete msg;
111 }
112
113 private:
114 Socket* socket_;
115};
116
deadbeefaea92932017-05-23 12:55:03 -0700117class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 public:
tommie7251592017-07-14 14:44:46 -0700119 CustomThread()
120 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700121 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000123
Yves Gerey665174f2018-06-19 15:03:05 +0200124 bool WrapCurrent() { return Thread::WrapCurrent(); }
125 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126};
127
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128// A thread that does nothing when it runs and signals an event
129// when it is destroyed.
130class SignalWhenDestroyedThread : public Thread {
131 public:
132 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700133 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
134 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135
Steve Anton9de3aac2017-10-24 10:08:26 -0700136 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 Stop();
138 event_->Set();
139 }
140
Steve Anton9de3aac2017-10-24 10:08:26 -0700141 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 // Do nothing.
143 }
144
145 private:
146 Event* event_;
147};
148
nissed9b75be2015-11-16 00:54:07 -0800149// A bool wrapped in a mutex, to avoid data races. Using a volatile
150// bool should be sufficient for correct code ("eventual consistency"
151// between caches is sufficient), but we can't tell the compiler about
152// that, and then tsan complains about a data race.
153
154// See also discussion at
155// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
156
157// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
158// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700159// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800160// performance critical, use a plain critical section for the time
161// being.
162
163class AtomicBool {
164 public:
165 explicit AtomicBool(bool value = false) : flag_(value) {}
166 AtomicBool& operator=(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200167 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800168 flag_ = value;
169 return *this;
170 }
171 bool get() const {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200172 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800173 return flag_;
174 }
175
176 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200177 mutable webrtc::Mutex mutex_;
nissed9b75be2015-11-16 00:54:07 -0800178 bool flag_;
179};
180
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181// Function objects to test Thread::Invoke.
182struct FunctorA {
183 int operator()() { return 42; }
184};
185class FunctorB {
186 public:
nissed9b75be2015-11-16 00:54:07 -0800187 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200188 void operator()() {
189 if (flag_)
190 *flag_ = true;
191 }
192
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193 private:
nissed9b75be2015-11-16 00:54:07 -0800194 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195};
196struct FunctorC {
197 int operator()() {
198 Thread::Current()->ProcessMessages(50);
199 return 24;
200 }
201};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700202struct FunctorD {
203 public:
204 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
205 FunctorD(FunctorD&&) = default;
Byoungchan Lee14af7622022-01-12 05:24:58 +0900206
207 FunctorD(const FunctorD&) = delete;
208 FunctorD& operator=(const FunctorD&) = delete;
209
Cameron Pickettd132ce12018-03-12 16:07:37 -0700210 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200211 void operator()() {
212 if (flag_)
213 *flag_ = true;
214 }
215
Cameron Pickettd132ce12018-03-12 16:07:37 -0700216 private:
217 AtomicBool* flag_;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700218};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219
220// See: https://code.google.com/p/webrtc/issues/detail?id=2409
221TEST(ThreadTest, DISABLED_Main) {
222 const SocketAddress addr("127.0.0.1", 0);
223
224 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700225 auto th1 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200226 Socket* socket = th1->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700227 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228
229 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700230 auto th2 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200231 Socket* asocket =
232 th2->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700233 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234
235 socket->Connect(sock_client.address());
236
tommie7251592017-07-14 14:44:46 -0700237 th1->Start();
238 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239
240 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700241 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242
243 // Give the clients a little while to run.
244 // Messages will be processed at 100, 300, 500, 700, 900.
245 Thread* th_main = Thread::Current();
246 th_main->ProcessMessages(1000);
247
248 // Stop the sending client. Give the receiver a bit longer to run, in case
249 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700250 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700252 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253
254 // Make sure the results were correct
255 EXPECT_EQ(5, msg_client.count);
256 EXPECT_EQ(34, msg_client.last);
257 EXPECT_EQ(5, sock_client.count);
258 EXPECT_EQ(55, sock_client.last);
259}
260
Tommife041642021-04-07 10:08:28 +0200261TEST(ThreadTest, CountBlockingCalls) {
Niels Möller83830f32022-05-20 09:12:57 +0200262 rtc::AutoThread current;
263
Tommife041642021-04-07 10:08:28 +0200264 // When the test runs, this will print out:
265 // (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
266 RTC_LOG_THREAD_BLOCK_COUNT();
267#if RTC_DCHECK_IS_ON
Tommife041642021-04-07 10:08:28 +0200268 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
269 [&](uint32_t actual_block, uint32_t could_block) {
270 EXPECT_EQ(1u, actual_block);
271 EXPECT_EQ(1u, could_block);
272 });
273
274 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
275 EXPECT_EQ(0u, blocked_calls.GetCouldBeBlockingCallCount());
276 EXPECT_EQ(0u, blocked_calls.GetTotalBlockedCallCount());
277
278 // Test invoking on the current thread. This should not count as an 'actual'
279 // invoke, but should still count as an invoke that could block since we
280 // that the call to Invoke serves a purpose in some configurations (and should
281 // not be used a general way to call methods on the same thread).
Niels Möller83830f32022-05-20 09:12:57 +0200282 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tommife041642021-04-07 10:08:28 +0200283 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
284 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
285 EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
286
287 // Create a new thread to invoke on.
288 auto thread = Thread::CreateWithSocketServer();
289 thread->Start();
290 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, []() { return 42; }));
291 EXPECT_EQ(1u, blocked_calls.GetBlockingCallCount());
292 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
293 EXPECT_EQ(2u, blocked_calls.GetTotalBlockedCallCount());
294 thread->Stop();
295 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2);
296#else
297 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
298 RTC_LOG(LS_INFO) << "Test not active in this config";
299#endif
300}
301
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200302#if RTC_DCHECK_IS_ON
303TEST(ThreadTest, CountBlockingCallsOneCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200304 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200305 bool was_called_back = false;
306 {
307 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
308 [&](uint32_t actual_block, uint32_t could_block) {
309 was_called_back = true;
310 });
Niels Möller83830f32022-05-20 09:12:57 +0200311 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200312 }
313 EXPECT_TRUE(was_called_back);
314}
315
316TEST(ThreadTest, CountBlockingCallsSkipCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200317 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200318 bool was_called_back = false;
319 {
320 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
321 [&](uint32_t actual_block, uint32_t could_block) {
322 was_called_back = true;
323 });
324 // Changed `blocked_calls` to not issue the callback if there are 1 or
325 // fewer blocking calls (i.e. we set the minimum required number to 2).
326 blocked_calls.set_minimum_call_count_for_callback(2);
Niels Möller83830f32022-05-20 09:12:57 +0200327 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200328 }
329 // We should not have gotten a call back.
330 EXPECT_FALSE(was_called_back);
331}
332#endif
333
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334// Test that setting thread names doesn't cause a malfunction.
335// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000336TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337 // Default name
tommie7251592017-07-14 14:44:46 -0700338 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 EXPECT_TRUE(thread->Start());
340 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700342 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800343 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344 EXPECT_TRUE(thread->Start());
345 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346 // Really long name
tommie7251592017-07-14 14:44:46 -0700347 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
349 EXPECT_TRUE(thread->Start());
350 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351}
352
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000353TEST(ThreadTest, Wrap) {
354 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200355 ThreadManager::Instance()->SetCurrentThread(nullptr);
356
357 {
358 CustomThread cthread;
359 EXPECT_TRUE(cthread.WrapCurrent());
360 EXPECT_EQ(&cthread, Thread::Current());
361 EXPECT_TRUE(cthread.RunningForTest());
362 EXPECT_FALSE(cthread.IsOwned());
363 cthread.UnwrapCurrent();
364 EXPECT_FALSE(cthread.RunningForTest());
365 }
366 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367}
368
Mirko Bonadei481e3452021-07-30 13:57:25 +0200369#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200370TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
Niels Möller83830f32022-05-20 09:12:57 +0200371 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200372 // Create and start the thread.
373 auto thread1 = Thread::CreateWithSocketServer();
374 auto thread2 = Thread::CreateWithSocketServer();
375
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200376 thread1->PostTask(
377 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200378 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200379}
380
381TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
Niels Möller83830f32022-05-20 09:12:57 +0200382 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200383 // Create and start the thread.
384 auto thread1 = Thread::CreateWithSocketServer();
385 auto thread2 = Thread::CreateWithSocketServer();
386 auto thread3 = Thread::CreateWithSocketServer();
387 auto thread4 = Thread::CreateWithSocketServer();
388
389 thread1->AllowInvokesToThread(thread2.get());
390 thread1->AllowInvokesToThread(thread3.get());
391
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200392 thread1->PostTask([&]() {
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200393 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
394 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
395 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200396 });
Niels Möller83830f32022-05-20 09:12:57 +0200397 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200398}
399
400TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
Niels Möller83830f32022-05-20 09:12:57 +0200401 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200402 // Create and start the thread.
403 auto thread1 = Thread::CreateWithSocketServer();
404 auto thread2 = Thread::CreateWithSocketServer();
405
406 thread1->DisallowAllInvokes();
407
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200408 thread1->PostTask(
409 [&]() { EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200410 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200411}
Mirko Bonadei481e3452021-07-30 13:57:25 +0200412#endif // (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200413
414TEST(ThreadTest, InvokesAllowedByDefault) {
Niels Möller83830f32022-05-20 09:12:57 +0200415 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200416 // Create and start the thread.
417 auto thread1 = Thread::CreateWithSocketServer();
418 auto thread2 = Thread::CreateWithSocketServer();
419
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200420 thread1->PostTask(
421 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); });
Niels Möller83830f32022-05-20 09:12:57 +0200422 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200423}
424
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000425TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000426 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700427 auto thread = Thread::CreateWithSocketServer();
428 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700430 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800431 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000432 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700433 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800434 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435 // Try calling bare functions.
436 struct LocalFuncs {
437 static int Func1() { return 999; }
438 static void Func2() {}
439 };
tommie7251592017-07-14 14:44:46 -0700440 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
441 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000442}
443
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000444// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100445// not deadlock but crash.
446#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
447TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200448 GTEST_FLAG_SET(death_test_style, "threadsafe");
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000449 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100450 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700451 auto other_thread = Thread::CreateWithSocketServer();
452 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100453 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
454 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
455 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000456}
457
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100458TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200459 GTEST_FLAG_SET(death_test_style, "threadsafe");
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100460 AutoThread thread;
461 Thread* first = Thread::Current();
462
463 auto second = Thread::Create();
464 second->Start();
465 auto third = Thread::Create();
466 third->Start();
467
468 second->Invoke<void>(RTC_FROM_HERE, [&] {
469 third->Invoke<void>(RTC_FROM_HERE, [&] {
470 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
471 });
472 });
473}
474
475#endif
476
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000477// Verifies that if thread A invokes a call on thread B and thread C is trying
478// to invoke A at the same time, thread A does not handle C's invoke while
479// invoking B.
480TEST(ThreadTest, ThreeThreadsInvoke) {
481 AutoThread thread;
482 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700483 auto thread_b = Thread::CreateWithSocketServer();
484 auto thread_c = Thread::CreateWithSocketServer();
485 thread_b->Start();
486 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000487
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000488 class LockedBool {
489 public:
490 explicit LockedBool(bool value) : value_(value) {}
491
492 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200493 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000494 value_ = value;
495 }
496
497 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200498 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000499 return value_;
500 }
501
502 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200503 webrtc::Mutex mutex_;
504 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000505 };
506
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000507 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000508 static void Set(LockedBool* out) { out->Set(true); }
509 static void InvokeSet(Thread* thread, LockedBool* out) {
Niels Möller1a29a5d2021-01-18 11:35:23 +0100510 thread->Invoke<void>(RTC_FROM_HERE, [out] { Set(out); });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000511 }
512
Artem Titov96e3b992021-07-26 16:03:14 +0200513 // Set `out` true and call InvokeSet on `thread`.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000514 static void SetAndInvokeSet(LockedBool* out,
515 Thread* thread,
516 LockedBool* out_inner) {
517 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000518 InvokeSet(thread, out_inner);
519 }
520
Artem Titov96e3b992021-07-26 16:03:14 +0200521 // Asynchronously invoke SetAndInvokeSet on `thread1` and wait until
522 // `thread1` starts the call.
Niels Möller0694ce72021-05-03 16:03:22 +0200523 static void AsyncInvokeSetAndWait(DEPRECATED_AsyncInvoker* invoker,
deadbeef162cb532017-02-23 17:10:07 -0800524 Thread* thread1,
525 Thread* thread2,
526 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000527 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000528
deadbeef162cb532017-02-23 17:10:07 -0800529 invoker->AsyncInvoke<void>(
Niels Möller1a29a5d2021-01-18 11:35:23 +0100530 RTC_FROM_HERE, thread1, [&async_invoked, thread2, out] {
531 SetAndInvokeSet(&async_invoked, thread2, out);
532 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000533
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000534 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000535 }
536 };
537
Niels Möller0694ce72021-05-03 16:03:22 +0200538 DEPRECATED_AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000539 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000540
541 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
542 // Thread B returns when C receives the call and C should be blocked until A
543 // starts to process messages.
Niels Möller1a29a5d2021-01-18 11:35:23 +0100544 Thread* thread_c_ptr = thread_c.get();
545 thread_b->Invoke<void>(
546 RTC_FROM_HERE, [&invoker, thread_c_ptr, thread_a, &thread_a_called] {
547 LocalFuncs::AsyncInvokeSetAndWait(&invoker, thread_c_ptr, thread_a,
548 &thread_a_called);
549 });
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000550 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000551
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000552 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000553}
554
Sebastian Jansson73387822020-01-16 11:15:35 +0100555class ThreadQueueTest : public ::testing::Test, public Thread {
556 public:
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100557 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {}
Sebastian Jansson73387822020-01-16 11:15:35 +0100558 bool IsLocked_Worker() {
559 if (!CritForTest()->TryEnter()) {
560 return true;
561 }
562 CritForTest()->Leave();
563 return false;
564 }
565 bool IsLocked() {
566 // We have to do this on a worker thread, or else the TryEnter will
567 // succeed, since our critical sections are reentrant.
568 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
569 worker->Start();
Niels Möller1a29a5d2021-01-18 11:35:23 +0100570 return worker->Invoke<bool>(RTC_FROM_HERE,
571 [this] { return IsLocked_Worker(); });
Sebastian Jansson73387822020-01-16 11:15:35 +0100572 }
573};
574
575struct DeletedLockChecker {
576 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
577 : test(test), was_locked(was_locked), deleted(deleted) {}
578 ~DeletedLockChecker() {
579 *deleted = true;
580 *was_locked = test->IsLocked();
581 }
582 ThreadQueueTest* test;
583 bool* was_locked;
584 bool* deleted;
585};
586
587static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
588 EXPECT_TRUE(q != nullptr);
589 int64_t now = TimeMillis();
590 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
591 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
592 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
593 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
594 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
595
596 Message msg;
597 for (size_t i = 0; i < 5; ++i) {
598 memset(&msg, 0, sizeof(msg));
599 EXPECT_TRUE(q->Get(&msg, 0));
600 EXPECT_EQ(i, msg.message_id);
601 }
602
603 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
604}
605
606TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100607 Thread q(CreateDefaultSocketServer(), true);
Sebastian Jansson73387822020-01-16 11:15:35 +0100608 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
609
610 NullSocketServer nullss;
611 Thread q_nullss(&nullss, true);
612 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
613}
614
615TEST_F(ThreadQueueTest, DisposeNotLocked) {
616 bool was_locked = true;
617 bool deleted = false;
618 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
619 Dispose(d);
620 Message msg;
621 EXPECT_FALSE(Get(&msg, 0));
622 EXPECT_TRUE(deleted);
623 EXPECT_FALSE(was_locked);
624}
625
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200626class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100627 public:
628 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
629 ~DeletedMessageHandler() override { *deleted_ = true; }
630 void OnMessage(Message* msg) override {}
631
632 private:
633 bool* deleted_;
634};
635
636TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
637 bool deleted = false;
638 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
639 // First, post a dispose.
640 Dispose(handler);
641 // Now, post a message, which should *not* be returned by Get().
642 Post(RTC_FROM_HERE, handler, 1);
643 Message msg;
644 EXPECT_FALSE(Get(&msg, 0));
645 EXPECT_TRUE(deleted);
646}
647
648// Ensure that ProcessAllMessageQueues does its essential function; process
649// all messages (both delayed and non delayed) up until the current time, on
650// all registered message queues.
651TEST(ThreadManager, ProcessAllMessageQueues) {
Niels Möller83830f32022-05-20 09:12:57 +0200652 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100653 Event entered_process_all_message_queues(true, false);
654 auto a = Thread::CreateWithSocketServer();
655 auto b = Thread::CreateWithSocketServer();
656 a->Start();
657 b->Start();
658
Niels Möller7a669002022-06-27 09:47:02 +0200659 std::atomic<int> messages_processed(0);
Sebastian Jansson73387822020-01-16 11:15:35 +0100660 auto incrementer = [&messages_processed,
661 &entered_process_all_message_queues] {
662 // Wait for event as a means to ensure Increment doesn't occur outside
663 // of ProcessAllMessageQueues. The event is set by a message posted to
664 // the main thread, which is guaranteed to be handled inside
665 // ProcessAllMessageQueues.
666 entered_process_all_message_queues.Wait(Event::kForever);
Niels Möller7a669002022-06-27 09:47:02 +0200667 messages_processed.fetch_add(1);
Sebastian Jansson73387822020-01-16 11:15:35 +0100668 };
669 auto event_signaler = [&entered_process_all_message_queues] {
670 entered_process_all_message_queues.Set();
671 };
672
673 // Post messages (both delayed and non delayed) to both threads.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200674 a->PostTask(incrementer);
675 b->PostTask(incrementer);
676 a->PostDelayedTask(incrementer, TimeDelta::Zero());
677 b->PostDelayedTask(incrementer, TimeDelta::Zero());
678 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100679
680 ThreadManager::ProcessAllMessageQueuesForTesting();
Niels Möller7a669002022-06-27 09:47:02 +0200681 EXPECT_EQ(4, messages_processed.load(std::memory_order_acquire));
Sebastian Jansson73387822020-01-16 11:15:35 +0100682}
683
684// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
685TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
686 auto t = Thread::CreateWithSocketServer();
687 t->Start();
688 t->Quit();
689 ThreadManager::ProcessAllMessageQueuesForTesting();
690}
691
692// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
693// messages.
694TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
Niels Möller83830f32022-05-20 09:12:57 +0200695 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100696 Event entered_process_all_message_queues(true, false);
697 auto t = Thread::CreateWithSocketServer();
698 t->Start();
699
700 auto clearer = [&entered_process_all_message_queues] {
701 // Wait for event as a means to ensure Clear doesn't occur outside of
702 // ProcessAllMessageQueues. The event is set by a message posted to the
703 // main thread, which is guaranteed to be handled inside
704 // ProcessAllMessageQueues.
705 entered_process_all_message_queues.Wait(Event::kForever);
706 rtc::Thread::Current()->Clear(nullptr);
707 };
708 auto event_signaler = [&entered_process_all_message_queues] {
709 entered_process_all_message_queues.Set();
710 };
711
712 // Post messages (both delayed and non delayed) to both threads.
Henrik Boström2deee4b2022-01-20 11:58:05 +0100713 t->PostTask(clearer);
Niels Möller83830f32022-05-20 09:12:57 +0200714 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100715 ThreadManager::ProcessAllMessageQueuesForTesting();
716}
717
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200718class RefCountedHandler : public MessageHandlerAutoCleanup,
719 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100720 public:
721 void OnMessage(Message* msg) override {}
722};
723
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200724class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100725 public:
726 void OnMessage(Message* msg) override {}
727};
728
729TEST(ThreadManager, ClearReentrant) {
730 std::unique_ptr<Thread> t(Thread::Create());
731 EmptyHandler handler;
732 RefCountedHandler* inner_handler(
733 new rtc::RefCountedObject<RefCountedHandler>());
734 // When the empty handler is destroyed, it will clear messages queued for
735 // itself. The message to be cleared itself wraps a MessageHandler object
736 // (RefCountedHandler) so this will cause the message queue to be cleared
737 // again in a re-entrant fashion, which previously triggered a DCHECK.
738 // The inner handler will be removed in a re-entrant fashion from the
739 // message queue of the thread while the outer handler is removed, verifying
740 // that the iterator is not invalidated in "MessageQueue::Clear".
741 t->Post(RTC_FROM_HERE, inner_handler, 0);
742 t->Post(RTC_FROM_HERE, &handler, 0,
743 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
744}
745
Tommi9ebe6d72021-11-16 16:07:34 +0100746class DEPRECATED_AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000747 public:
748 void IntCallback(int value) {
749 EXPECT_EQ(expected_thread_, Thread::Current());
750 int_value_ = value;
751 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 void SetExpectedThreadForIntCallback(Thread* thread) {
753 expected_thread_ = thread;
754 }
755
756 protected:
757 enum { kWaitTimeout = 1000 };
Tommi9ebe6d72021-11-16 16:07:34 +0100758 DEPRECATED_AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759
Niels Möller83830f32022-05-20 09:12:57 +0200760 rtc::AutoThread main_thread_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 Thread* expected_thread_;
763};
764
Tommi9ebe6d72021-11-16 16:07:34 +0100765TEST_F(DEPRECATED_AsyncInvokeTest, FireAndForget) {
Niels Möller0694ce72021-05-03 16:03:22 +0200766 DEPRECATED_AsyncInvoker invoker;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700768 auto thread = Thread::CreateWithSocketServer();
769 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000770 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800771 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700772 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800773 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700774 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000775}
776
Tommi9ebe6d72021-11-16 16:07:34 +0100777TEST_F(DEPRECATED_AsyncInvokeTest, NonCopyableFunctor) {
Niels Möller0694ce72021-05-03 16:03:22 +0200778 DEPRECATED_AsyncInvoker invoker;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700779 // Create and start the thread.
780 auto thread = Thread::CreateWithSocketServer();
781 thread->Start();
782 // Try calling functor.
783 AtomicBool called;
784 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
785 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
786 thread->Stop();
787}
788
Tommi9ebe6d72021-11-16 16:07:34 +0100789TEST_F(DEPRECATED_AsyncInvokeTest, KillInvokerDuringExecute) {
deadbeef162cb532017-02-23 17:10:07 -0800790 // Use these events to get in a state where the functor is in the middle of
791 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
792 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100793 Event functor_started;
794 Event functor_continue;
795 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800796
tommie7251592017-07-14 14:44:46 -0700797 auto thread = Thread::CreateWithSocketServer();
798 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800799 volatile bool invoker_destroyed = false;
800 {
deadbeef3af63b02017-08-08 17:59:47 -0700801 auto functor = [&functor_started, &functor_continue, &functor_finished,
802 &invoker_destroyed] {
803 functor_started.Set();
804 functor_continue.Wait(Event::kForever);
805 rtc::Thread::Current()->SleepMs(kWaitTimeout);
806 EXPECT_FALSE(invoker_destroyed);
807 functor_finished.Set();
808 };
Niels Möller0694ce72021-05-03 16:03:22 +0200809 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700810 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800811 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700812
deadbeef3af63b02017-08-08 17:59:47 -0700813 // Destroy the invoker while the functor is still executing (doing
814 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700815 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800816 }
817
818 // If the destructor DIDN'T wait for the functor to finish executing, it will
819 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
820 // second.
821 invoker_destroyed = true;
822 functor_finished.Wait(Event::kForever);
823}
824
deadbeef3af63b02017-08-08 17:59:47 -0700825// Variant of the above test where the async-invoked task calls AsyncInvoke
Tommi9ebe6d72021-11-16 16:07:34 +0100826// *again*, for the thread on which the invoker is currently being destroyed.
827// This shouldn't deadlock or crash. The second invocation should be ignored.
828TEST_F(DEPRECATED_AsyncInvokeTest,
829 KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100830 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700831 // Flag used to verify that the recursively invoked task never actually runs.
832 bool reentrant_functor_run = false;
833
834 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200835 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700836 thread.Start();
837 {
Niels Möller0694ce72021-05-03 16:03:22 +0200838 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700839 auto reentrant_functor = [&reentrant_functor_run] {
840 reentrant_functor_run = true;
841 };
842 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
843 functor_started.Set();
844 Thread::Current()->SleepMs(kWaitTimeout);
845 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
846 };
Artem Titov96e3b992021-07-26 16:03:14 +0200847 // This queues a task on `thread` to sleep for `kWaitTimeout` then queue a
848 // task on `main`. But this second queued task should never run, since the
deadbeef3af63b02017-08-08 17:59:47 -0700849 // destructor will be entered before it's even invoked.
850 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
851 functor_started.Wait(Event::kForever);
852 }
853 EXPECT_FALSE(reentrant_functor_run);
854}
855
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100856void WaitAndSetEvent(Event* wait_event, Event* set_event) {
857 wait_event->Wait(Event::kForever);
858 set_event->Set();
859}
860
861// A functor that keeps track of the number of copies and moves.
862class LifeCycleFunctor {
863 public:
864 struct Stats {
865 size_t copy_count = 0;
866 size_t move_count = 0;
867 };
868
869 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
870 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
871 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
872
873 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
874 stats_ = other.stats_;
875 event_ = other.event_;
876 ++stats_->copy_count;
877 return *this;
878 }
879
880 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
881 stats_ = other.stats_;
882 event_ = other.event_;
883 ++stats_->move_count;
884 return *this;
885 }
886
887 void operator()() { event_->Set(); }
888
889 private:
890 Stats* stats_;
891 Event* event_;
892};
893
894// A functor that verifies the thread it was destroyed on.
895class DestructionFunctor {
896 public:
897 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
898 : thread_(thread),
899 thread_was_current_(thread_was_current),
900 event_(event) {}
901 ~DestructionFunctor() {
902 // Only signal the event if this was the functor that was invoked to avoid
903 // the event being signaled due to the destruction of temporary/moved
904 // versions of this object.
905 if (was_invoked_) {
906 *thread_was_current_ = thread_->IsCurrent();
907 event_->Set();
908 }
909 }
910
911 void operator()() { was_invoked_ = true; }
912
913 private:
914 Thread* thread_;
915 bool* thread_was_current_;
916 Event* event_;
917 bool was_invoked_ = false;
918};
919
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100920TEST(ThreadPostTaskTest, InvokesWithLambda) {
921 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
922 background_thread->Start();
923
924 Event event;
Henrik Boström595f6882022-01-24 09:57:03 +0100925 background_thread->PostTask([&event] { event.Set(); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100926 event.Wait(Event::kForever);
927}
928
929TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
930 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
931 background_thread->Start();
932
933 LifeCycleFunctor::Stats stats;
934 Event event;
935 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100936 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100937 event.Wait(Event::kForever);
938
939 EXPECT_EQ(1u, stats.copy_count);
940 EXPECT_EQ(0u, stats.move_count);
941}
942
943TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
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(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100951 event.Wait(Event::kForever);
952
953 EXPECT_EQ(0u, stats.copy_count);
954 EXPECT_EQ(1u, stats.move_count);
955}
956
957TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
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);
964 LifeCycleFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +0100965 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100966 event.Wait(Event::kForever);
967
968 EXPECT_EQ(1u, stats.copy_count);
969 EXPECT_EQ(0u, stats.move_count);
970}
971
972TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
973 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
974 background_thread->Start();
975
976 Event event;
977 bool was_invoked_on_background_thread = false;
978 DestructionFunctor functor(background_thread.get(),
979 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100980 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100981 event.Wait(Event::kForever);
982
983 EXPECT_TRUE(was_invoked_on_background_thread);
984}
985
986TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
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(std::move(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,
1001 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
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);
1009 DestructionFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +01001010 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001011 event.Wait(Event::kForever);
1012
1013 EXPECT_TRUE(was_invoked_on_background_thread);
1014}
1015
1016TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
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;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001022 Thread* background_thread_ptr = background_thread.get();
Henrik Boström595f6882022-01-24 09:57:03 +01001023 background_thread->PostTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001024 [background_thread_ptr, &was_invoked_on_background_thread, &event] {
1025 was_invoked_on_background_thread = background_thread_ptr->IsCurrent();
1026 event.Set();
1027 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001028 event.Wait(Event::kForever);
1029
1030 EXPECT_TRUE(was_invoked_on_background_thread);
1031}
1032
1033TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1034 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1035 background_thread->Start();
1036
1037 // The first event ensures that SendSingleMessage() is not blocking this
1038 // thread. The second event ensures that the message is processed.
1039 Event event_set_by_test_thread;
1040 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001041 background_thread->PostTask(
Henrik Boström2deee4b2022-01-20 11:58:05 +01001042 [&event_set_by_test_thread, &event_set_by_background_thread] {
1043 WaitAndSetEvent(&event_set_by_test_thread,
1044 &event_set_by_background_thread);
1045 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001046 event_set_by_test_thread.Set();
1047 event_set_by_background_thread.Wait(Event::kForever);
1048}
1049
1050TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1051 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1052 background_thread->Start();
1053
1054 Event first;
1055 Event second;
1056 Event third;
1057 Event fourth;
1058
Henrik Boström595f6882022-01-24 09:57:03 +01001059 background_thread->PostTask(
1060 [&first, &second] { WaitAndSetEvent(&first, &second); });
1061 background_thread->PostTask(
1062 [&second, &third] { WaitAndSetEvent(&second, &third); });
1063 background_thread->PostTask(
1064 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001065
1066 // All tasks have been posted before the first one is unblocked.
1067 first.Set();
1068 // Only if the chain is invoked in posted order will the last event be set.
1069 fourth.Wait(Event::kForever);
1070}
1071
Steve Antonbcc1a762019-12-11 11:21:53 -08001072TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1073 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1074 background_thread->Start();
1075
1076 // The first event ensures that SendSingleMessage() is not blocking this
1077 // thread. The second event ensures that the message is processed.
1078 Event event_set_by_test_thread;
1079 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001080 background_thread->PostDelayedTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001081 [&event_set_by_test_thread, &event_set_by_background_thread] {
1082 WaitAndSetEvent(&event_set_by_test_thread,
1083 &event_set_by_background_thread);
1084 },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001085 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001086 event_set_by_test_thread.Set();
1087 event_set_by_background_thread.Wait(Event::kForever);
1088}
1089
1090TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001091 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001092 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1093 background_thread->Start();
1094
1095 Event first;
1096 Event second;
1097 Event third;
1098 Event fourth;
1099
Henrik Boström595f6882022-01-24 09:57:03 +01001100 background_thread->PostDelayedTask(
1101 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001102 TimeDelta::Millis(11));
Henrik Boström595f6882022-01-24 09:57:03 +01001103 background_thread->PostDelayedTask(
1104 [&first, &second] { WaitAndSetEvent(&first, &second); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001105 TimeDelta::Millis(9));
Henrik Boström595f6882022-01-24 09:57:03 +01001106 background_thread->PostDelayedTask(
1107 [&second, &third] { WaitAndSetEvent(&second, &third); },
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001108 TimeDelta::Millis(10));
Steve Antonbcc1a762019-12-11 11:21:53 -08001109
1110 // All tasks have been posted before the first one is unblocked.
1111 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001112 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov4bcf8092022-07-06 19:42:34 +02001113 clock.AdvanceTime(TimeDelta::Millis(11));
Markus Handell2cfc1af2022-08-19 08:16:48 +00001114 EXPECT_TRUE(fourth.Wait(TimeDelta::Zero()));
Steve Antonbcc1a762019-12-11 11:21:53 -08001115}
1116
Tommi6866dc72020-05-15 10:11:56 +02001117TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1118 auto current_tq = webrtc::TaskQueueBase::Current();
1119 {
1120 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1121 thread->WrapCurrent();
1122 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1123 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1124 thread->UnwrapCurrent();
1125 }
1126 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1127}
1128
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001129class ThreadFactory : public webrtc::TaskQueueFactory {
1130 public:
1131 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1132 CreateTaskQueue(absl::string_view /* name */,
1133 Priority /*priority*/) const override {
1134 std::unique_ptr<Thread> thread = Thread::Create();
1135 thread->Start();
1136 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1137 thread.release());
1138 }
1139};
1140
1141using ::webrtc::TaskQueueTest;
1142
1143INSTANTIATE_TEST_SUITE_P(RtcThread,
1144 TaskQueueTest,
1145 ::testing::Values(std::make_unique<ThreadFactory>));
1146
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001147} // namespace
1148} // namespace rtc