blob: 5490e6171e3bd9fa8a243f229437ab1904b71d19 [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"
Artem Titovc374d112022-06-16 21:27:45 +020017#include "api/task_queue/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080018#include "rtc_base/async_invoker.h"
19#include "rtc_base/async_udp_socket.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010020#include "rtc_base/atomic_ops.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020021#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/event.h"
23#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"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010030#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031
32#if defined(WEBRTC_WIN)
33#include <comdef.h> // NOLINT
Markus Handell4ab7dde2020-07-10 13:23:25 +020034
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035#endif
36
Mirko Bonadeie10b1632018-12-11 18:43:40 +010037namespace rtc {
38namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039
Sebastian Jansson73387822020-01-16 11:15:35 +010040using ::webrtc::ToQueuedTask;
41
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042// Generates a sequence of numbers (collaboratively).
43class TestGenerator {
44 public:
45 TestGenerator() : last(0), count(0) {}
46
47 int Next(int prev) {
48 int result = prev + last;
49 last = result;
50 count += 1;
51 return result;
52 }
53
54 int last;
55 int count;
56};
57
58struct TestMessage : public MessageData {
59 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060
61 int value;
62};
63
64// Receives on a socket and sends by posting messages.
65class SocketClient : public TestGenerator, public sigslot::has_slots<> {
66 public:
Niels Möllerd0b88792021-08-12 10:32:30 +020067 SocketClient(Socket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +020068 const SocketAddress& addr,
69 Thread* post_thread,
70 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071 : socket_(AsyncUDPSocket::Create(socket, addr)),
72 post_thread_(post_thread),
73 post_handler_(phandler) {
74 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
75 }
76
Steve Anton9de3aac2017-10-24 10:08:26 -070077 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078
79 SocketAddress address() const { return socket_->GetLocalAddress(); }
80
Yves Gerey665174f2018-06-19 15:03:05 +020081 void OnPacket(AsyncPacketSocket* socket,
82 const char* buf,
83 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010085 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020086 EXPECT_EQ(size, sizeof(uint32_t));
87 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
88 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000089
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070090 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
91 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092 }
93
94 private:
95 AsyncUDPSocket* socket_;
96 Thread* post_thread_;
97 MessageHandler* post_handler_;
98};
99
100// Receives messages and sends on a socket.
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200101class MessageClient : public MessageHandlerAutoCleanup, public TestGenerator {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200103 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104
Steve Anton9de3aac2017-10-24 10:08:26 -0700105 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106
Steve Anton9de3aac2017-10-24 10:08:26 -0700107 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
109 int result = Next(msg->value);
110 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
111 delete msg;
112 }
113
114 private:
115 Socket* socket_;
116};
117
deadbeefaea92932017-05-23 12:55:03 -0700118class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 public:
tommie7251592017-07-14 14:44:46 -0700120 CustomThread()
121 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700122 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000124
Yves Gerey665174f2018-06-19 15:03:05 +0200125 bool WrapCurrent() { return Thread::WrapCurrent(); }
126 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127};
128
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129// A thread that does nothing when it runs and signals an event
130// when it is destroyed.
131class SignalWhenDestroyedThread : public Thread {
132 public:
133 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700134 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
135 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136
Steve Anton9de3aac2017-10-24 10:08:26 -0700137 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 Stop();
139 event_->Set();
140 }
141
Steve Anton9de3aac2017-10-24 10:08:26 -0700142 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 // Do nothing.
144 }
145
146 private:
147 Event* event_;
148};
149
nissed9b75be2015-11-16 00:54:07 -0800150// A bool wrapped in a mutex, to avoid data races. Using a volatile
151// bool should be sufficient for correct code ("eventual consistency"
152// between caches is sufficient), but we can't tell the compiler about
153// that, and then tsan complains about a data race.
154
155// See also discussion at
156// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
157
158// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
159// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700160// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800161// performance critical, use a plain critical section for the time
162// being.
163
164class AtomicBool {
165 public:
166 explicit AtomicBool(bool value = false) : flag_(value) {}
167 AtomicBool& operator=(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200168 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800169 flag_ = value;
170 return *this;
171 }
172 bool get() const {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200173 webrtc::MutexLock scoped_lock(&mutex_);
nissed9b75be2015-11-16 00:54:07 -0800174 return flag_;
175 }
176
177 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200178 mutable webrtc::Mutex mutex_;
nissed9b75be2015-11-16 00:54:07 -0800179 bool flag_;
180};
181
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182// Function objects to test Thread::Invoke.
183struct FunctorA {
184 int operator()() { return 42; }
185};
186class FunctorB {
187 public:
nissed9b75be2015-11-16 00:54:07 -0800188 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200189 void operator()() {
190 if (flag_)
191 *flag_ = true;
192 }
193
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 private:
nissed9b75be2015-11-16 00:54:07 -0800195 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196};
197struct FunctorC {
198 int operator()() {
199 Thread::Current()->ProcessMessages(50);
200 return 24;
201 }
202};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700203struct FunctorD {
204 public:
205 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
206 FunctorD(FunctorD&&) = default;
Byoungchan Lee14af7622022-01-12 05:24:58 +0900207
208 FunctorD(const FunctorD&) = delete;
209 FunctorD& operator=(const FunctorD&) = delete;
210
Cameron Pickettd132ce12018-03-12 16:07:37 -0700211 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200212 void operator()() {
213 if (flag_)
214 *flag_ = true;
215 }
216
Cameron Pickettd132ce12018-03-12 16:07:37 -0700217 private:
218 AtomicBool* flag_;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700219};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
221// See: https://code.google.com/p/webrtc/issues/detail?id=2409
222TEST(ThreadTest, DISABLED_Main) {
223 const SocketAddress addr("127.0.0.1", 0);
224
225 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700226 auto th1 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200227 Socket* socket = th1->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700228 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700231 auto th2 = Thread::CreateWithSocketServer();
Niels Möllerd0b88792021-08-12 10:32:30 +0200232 Socket* asocket =
233 th2->socketserver()->CreateSocket(addr.family(), SOCK_DGRAM);
tommie7251592017-07-14 14:44:46 -0700234 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235
236 socket->Connect(sock_client.address());
237
tommie7251592017-07-14 14:44:46 -0700238 th1->Start();
239 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
241 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700242 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243
244 // Give the clients a little while to run.
245 // Messages will be processed at 100, 300, 500, 700, 900.
246 Thread* th_main = Thread::Current();
247 th_main->ProcessMessages(1000);
248
249 // Stop the sending client. Give the receiver a bit longer to run, in case
250 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700251 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700253 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
255 // Make sure the results were correct
256 EXPECT_EQ(5, msg_client.count);
257 EXPECT_EQ(34, msg_client.last);
258 EXPECT_EQ(5, sock_client.count);
259 EXPECT_EQ(55, sock_client.last);
260}
261
Tommife041642021-04-07 10:08:28 +0200262TEST(ThreadTest, CountBlockingCalls) {
Niels Möller83830f32022-05-20 09:12:57 +0200263 rtc::AutoThread current;
264
Tommife041642021-04-07 10:08:28 +0200265 // When the test runs, this will print out:
266 // (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
267 RTC_LOG_THREAD_BLOCK_COUNT();
268#if RTC_DCHECK_IS_ON
Tommife041642021-04-07 10:08:28 +0200269 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
270 [&](uint32_t actual_block, uint32_t could_block) {
271 EXPECT_EQ(1u, actual_block);
272 EXPECT_EQ(1u, could_block);
273 });
274
275 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
276 EXPECT_EQ(0u, blocked_calls.GetCouldBeBlockingCallCount());
277 EXPECT_EQ(0u, blocked_calls.GetTotalBlockedCallCount());
278
279 // Test invoking on the current thread. This should not count as an 'actual'
280 // invoke, but should still count as an invoke that could block since we
281 // that the call to Invoke serves a purpose in some configurations (and should
282 // not be used a general way to call methods on the same thread).
Niels Möller83830f32022-05-20 09:12:57 +0200283 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tommife041642021-04-07 10:08:28 +0200284 EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
285 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
286 EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
287
288 // Create a new thread to invoke on.
289 auto thread = Thread::CreateWithSocketServer();
290 thread->Start();
291 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, []() { return 42; }));
292 EXPECT_EQ(1u, blocked_calls.GetBlockingCallCount());
293 EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
294 EXPECT_EQ(2u, blocked_calls.GetTotalBlockedCallCount());
295 thread->Stop();
296 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2);
297#else
298 RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0);
299 RTC_LOG(LS_INFO) << "Test not active in this config";
300#endif
301}
302
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200303#if RTC_DCHECK_IS_ON
304TEST(ThreadTest, CountBlockingCallsOneCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200305 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200306 bool was_called_back = false;
307 {
308 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
309 [&](uint32_t actual_block, uint32_t could_block) {
310 was_called_back = true;
311 });
Niels Möller83830f32022-05-20 09:12:57 +0200312 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200313 }
314 EXPECT_TRUE(was_called_back);
315}
316
317TEST(ThreadTest, CountBlockingCallsSkipCallback) {
Niels Möller83830f32022-05-20 09:12:57 +0200318 rtc::AutoThread current;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200319 bool was_called_back = false;
320 {
321 rtc::Thread::ScopedCountBlockingCalls blocked_calls(
322 [&](uint32_t actual_block, uint32_t could_block) {
323 was_called_back = true;
324 });
325 // Changed `blocked_calls` to not issue the callback if there are 1 or
326 // fewer blocking calls (i.e. we set the minimum required number to 2).
327 blocked_calls.set_minimum_call_count_for_callback(2);
Niels Möller83830f32022-05-20 09:12:57 +0200328 current.Invoke<void>(RTC_FROM_HERE, []() {});
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200329 }
330 // We should not have gotten a call back.
331 EXPECT_FALSE(was_called_back);
332}
333#endif
334
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335// Test that setting thread names doesn't cause a malfunction.
336// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000337TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338 // Default name
tommie7251592017-07-14 14:44:46 -0700339 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 EXPECT_TRUE(thread->Start());
341 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700343 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800344 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345 EXPECT_TRUE(thread->Start());
346 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347 // Really long name
tommie7251592017-07-14 14:44:46 -0700348 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
350 EXPECT_TRUE(thread->Start());
351 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352}
353
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000354TEST(ThreadTest, Wrap) {
355 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200356 ThreadManager::Instance()->SetCurrentThread(nullptr);
357
358 {
359 CustomThread cthread;
360 EXPECT_TRUE(cthread.WrapCurrent());
361 EXPECT_EQ(&cthread, Thread::Current());
362 EXPECT_TRUE(cthread.RunningForTest());
363 EXPECT_FALSE(cthread.IsOwned());
364 cthread.UnwrapCurrent();
365 EXPECT_FALSE(cthread.RunningForTest());
366 }
367 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368}
369
Mirko Bonadei481e3452021-07-30 13:57:25 +0200370#if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200371TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
Niels Möller83830f32022-05-20 09:12:57 +0200372 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200373 // Create and start the thread.
374 auto thread1 = Thread::CreateWithSocketServer();
375 auto thread2 = Thread::CreateWithSocketServer();
376
377 thread1->PostTask(ToQueuedTask(
378 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
Niels Möller83830f32022-05-20 09:12:57 +0200379 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200380}
381
382TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
Niels Möller83830f32022-05-20 09:12:57 +0200383 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200384 // Create and start the thread.
385 auto thread1 = Thread::CreateWithSocketServer();
386 auto thread2 = Thread::CreateWithSocketServer();
387 auto thread3 = Thread::CreateWithSocketServer();
388 auto thread4 = Thread::CreateWithSocketServer();
389
390 thread1->AllowInvokesToThread(thread2.get());
391 thread1->AllowInvokesToThread(thread3.get());
392
393 thread1->PostTask(ToQueuedTask([&]() {
394 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
395 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
396 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
397 }));
Niels Möller83830f32022-05-20 09:12:57 +0200398 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200399}
400
401TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
Niels Möller83830f32022-05-20 09:12:57 +0200402 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200403 // Create and start the thread.
404 auto thread1 = Thread::CreateWithSocketServer();
405 auto thread2 = Thread::CreateWithSocketServer();
406
407 thread1->DisallowAllInvokes();
408
409 thread1->PostTask(ToQueuedTask([&]() {
410 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
411 }));
Niels Möller83830f32022-05-20 09:12:57 +0200412 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200413}
Mirko Bonadei481e3452021-07-30 13:57:25 +0200414#endif // (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200415
416TEST(ThreadTest, InvokesAllowedByDefault) {
Niels Möller83830f32022-05-20 09:12:57 +0200417 rtc::AutoThread main_thread;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200418 // Create and start the thread.
419 auto thread1 = Thread::CreateWithSocketServer();
420 auto thread2 = Thread::CreateWithSocketServer();
421
422 thread1->PostTask(ToQueuedTask(
423 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
Niels Möller83830f32022-05-20 09:12:57 +0200424 main_thread.ProcessMessages(100);
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200425}
426
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000427TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700429 auto thread = Thread::CreateWithSocketServer();
430 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700432 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800433 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700435 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800436 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437 // Try calling bare functions.
438 struct LocalFuncs {
439 static int Func1() { return 999; }
440 static void Func2() {}
441 };
tommie7251592017-07-14 14:44:46 -0700442 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
443 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444}
445
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000446// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100447// not deadlock but crash.
448#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
449TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200450 GTEST_FLAG_SET(death_test_style, "threadsafe");
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000451 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100452 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700453 auto other_thread = Thread::CreateWithSocketServer();
454 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100455 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
456 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
457 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000458}
459
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100460TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
Mirko Bonadei386b5c32021-07-28 08:55:52 +0200461 GTEST_FLAG_SET(death_test_style, "threadsafe");
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100462 AutoThread thread;
463 Thread* first = Thread::Current();
464
465 auto second = Thread::Create();
466 second->Start();
467 auto third = Thread::Create();
468 third->Start();
469
470 second->Invoke<void>(RTC_FROM_HERE, [&] {
471 third->Invoke<void>(RTC_FROM_HERE, [&] {
472 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
473 });
474 });
475}
476
477#endif
478
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000479// Verifies that if thread A invokes a call on thread B and thread C is trying
480// to invoke A at the same time, thread A does not handle C's invoke while
481// invoking B.
482TEST(ThreadTest, ThreeThreadsInvoke) {
483 AutoThread thread;
484 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700485 auto thread_b = Thread::CreateWithSocketServer();
486 auto thread_c = Thread::CreateWithSocketServer();
487 thread_b->Start();
488 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000489
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000490 class LockedBool {
491 public:
492 explicit LockedBool(bool value) : value_(value) {}
493
494 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200495 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000496 value_ = value;
497 }
498
499 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200500 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000501 return value_;
502 }
503
504 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200505 webrtc::Mutex mutex_;
506 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000507 };
508
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000509 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000510 static void Set(LockedBool* out) { out->Set(true); }
511 static void InvokeSet(Thread* thread, LockedBool* out) {
Niels Möller1a29a5d2021-01-18 11:35:23 +0100512 thread->Invoke<void>(RTC_FROM_HERE, [out] { Set(out); });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000513 }
514
Artem Titov96e3b992021-07-26 16:03:14 +0200515 // Set `out` true and call InvokeSet on `thread`.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000516 static void SetAndInvokeSet(LockedBool* out,
517 Thread* thread,
518 LockedBool* out_inner) {
519 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000520 InvokeSet(thread, out_inner);
521 }
522
Artem Titov96e3b992021-07-26 16:03:14 +0200523 // Asynchronously invoke SetAndInvokeSet on `thread1` and wait until
524 // `thread1` starts the call.
Niels Möller0694ce72021-05-03 16:03:22 +0200525 static void AsyncInvokeSetAndWait(DEPRECATED_AsyncInvoker* invoker,
deadbeef162cb532017-02-23 17:10:07 -0800526 Thread* thread1,
527 Thread* thread2,
528 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000529 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000530
deadbeef162cb532017-02-23 17:10:07 -0800531 invoker->AsyncInvoke<void>(
Niels Möller1a29a5d2021-01-18 11:35:23 +0100532 RTC_FROM_HERE, thread1, [&async_invoked, thread2, out] {
533 SetAndInvokeSet(&async_invoked, thread2, out);
534 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000535
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000536 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000537 }
538 };
539
Niels Möller0694ce72021-05-03 16:03:22 +0200540 DEPRECATED_AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000541 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000542
543 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
544 // Thread B returns when C receives the call and C should be blocked until A
545 // starts to process messages.
Niels Möller1a29a5d2021-01-18 11:35:23 +0100546 Thread* thread_c_ptr = thread_c.get();
547 thread_b->Invoke<void>(
548 RTC_FROM_HERE, [&invoker, thread_c_ptr, thread_a, &thread_a_called] {
549 LocalFuncs::AsyncInvokeSetAndWait(&invoker, thread_c_ptr, thread_a,
550 &thread_a_called);
551 });
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000552 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000553
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000554 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000555}
556
Sebastian Jansson73387822020-01-16 11:15:35 +0100557class ThreadQueueTest : public ::testing::Test, public Thread {
558 public:
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100559 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {}
Sebastian Jansson73387822020-01-16 11:15:35 +0100560 bool IsLocked_Worker() {
561 if (!CritForTest()->TryEnter()) {
562 return true;
563 }
564 CritForTest()->Leave();
565 return false;
566 }
567 bool IsLocked() {
568 // We have to do this on a worker thread, or else the TryEnter will
569 // succeed, since our critical sections are reentrant.
570 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
571 worker->Start();
Niels Möller1a29a5d2021-01-18 11:35:23 +0100572 return worker->Invoke<bool>(RTC_FROM_HERE,
573 [this] { return IsLocked_Worker(); });
Sebastian Jansson73387822020-01-16 11:15:35 +0100574 }
575};
576
577struct DeletedLockChecker {
578 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
579 : test(test), was_locked(was_locked), deleted(deleted) {}
580 ~DeletedLockChecker() {
581 *deleted = true;
582 *was_locked = test->IsLocked();
583 }
584 ThreadQueueTest* test;
585 bool* was_locked;
586 bool* deleted;
587};
588
589static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
590 EXPECT_TRUE(q != nullptr);
591 int64_t now = TimeMillis();
592 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
593 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
594 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
595 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
596 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
597
598 Message msg;
599 for (size_t i = 0; i < 5; ++i) {
600 memset(&msg, 0, sizeof(msg));
601 EXPECT_TRUE(q->Get(&msg, 0));
602 EXPECT_EQ(i, msg.message_id);
603 }
604
605 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
606}
607
608TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100609 Thread q(CreateDefaultSocketServer(), true);
Sebastian Jansson73387822020-01-16 11:15:35 +0100610 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
611
612 NullSocketServer nullss;
613 Thread q_nullss(&nullss, true);
614 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
615}
616
617TEST_F(ThreadQueueTest, DisposeNotLocked) {
618 bool was_locked = true;
619 bool deleted = false;
620 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
621 Dispose(d);
622 Message msg;
623 EXPECT_FALSE(Get(&msg, 0));
624 EXPECT_TRUE(deleted);
625 EXPECT_FALSE(was_locked);
626}
627
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200628class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100629 public:
630 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
631 ~DeletedMessageHandler() override { *deleted_ = true; }
632 void OnMessage(Message* msg) override {}
633
634 private:
635 bool* deleted_;
636};
637
638TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
639 bool deleted = false;
640 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
641 // First, post a dispose.
642 Dispose(handler);
643 // Now, post a message, which should *not* be returned by Get().
644 Post(RTC_FROM_HERE, handler, 1);
645 Message msg;
646 EXPECT_FALSE(Get(&msg, 0));
647 EXPECT_TRUE(deleted);
648}
649
650// Ensure that ProcessAllMessageQueues does its essential function; process
651// all messages (both delayed and non delayed) up until the current time, on
652// all registered message queues.
653TEST(ThreadManager, ProcessAllMessageQueues) {
Niels Möller83830f32022-05-20 09:12:57 +0200654 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100655 Event entered_process_all_message_queues(true, false);
656 auto a = Thread::CreateWithSocketServer();
657 auto b = Thread::CreateWithSocketServer();
658 a->Start();
659 b->Start();
660
661 volatile int messages_processed = 0;
662 auto incrementer = [&messages_processed,
663 &entered_process_all_message_queues] {
664 // Wait for event as a means to ensure Increment doesn't occur outside
665 // of ProcessAllMessageQueues. The event is set by a message posted to
666 // the main thread, which is guaranteed to be handled inside
667 // ProcessAllMessageQueues.
668 entered_process_all_message_queues.Wait(Event::kForever);
669 AtomicOps::Increment(&messages_processed);
670 };
671 auto event_signaler = [&entered_process_all_message_queues] {
672 entered_process_all_message_queues.Set();
673 };
674
675 // Post messages (both delayed and non delayed) to both threads.
676 a->PostTask(ToQueuedTask(incrementer));
677 b->PostTask(ToQueuedTask(incrementer));
678 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
679 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
Niels Möller83830f32022-05-20 09:12:57 +0200680 main_thread.PostTask(ToQueuedTask(event_signaler));
Sebastian Jansson73387822020-01-16 11:15:35 +0100681
682 ThreadManager::ProcessAllMessageQueuesForTesting();
683 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
684}
685
686// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
687TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
688 auto t = Thread::CreateWithSocketServer();
689 t->Start();
690 t->Quit();
691 ThreadManager::ProcessAllMessageQueuesForTesting();
692}
693
694// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
695// messages.
696TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
Niels Möller83830f32022-05-20 09:12:57 +0200697 rtc::AutoThread main_thread;
Sebastian Jansson73387822020-01-16 11:15:35 +0100698 Event entered_process_all_message_queues(true, false);
699 auto t = Thread::CreateWithSocketServer();
700 t->Start();
701
702 auto clearer = [&entered_process_all_message_queues] {
703 // Wait for event as a means to ensure Clear doesn't occur outside of
704 // ProcessAllMessageQueues. The event is set by a message posted to the
705 // main thread, which is guaranteed to be handled inside
706 // ProcessAllMessageQueues.
707 entered_process_all_message_queues.Wait(Event::kForever);
708 rtc::Thread::Current()->Clear(nullptr);
709 };
710 auto event_signaler = [&entered_process_all_message_queues] {
711 entered_process_all_message_queues.Set();
712 };
713
714 // Post messages (both delayed and non delayed) to both threads.
Henrik Boström2deee4b2022-01-20 11:58:05 +0100715 t->PostTask(clearer);
Niels Möller83830f32022-05-20 09:12:57 +0200716 main_thread.PostTask(event_signaler);
Sebastian Jansson73387822020-01-16 11:15:35 +0100717 ThreadManager::ProcessAllMessageQueuesForTesting();
718}
719
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200720class RefCountedHandler : public MessageHandlerAutoCleanup,
721 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100722 public:
723 void OnMessage(Message* msg) override {}
724};
725
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200726class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100727 public:
728 void OnMessage(Message* msg) override {}
729};
730
731TEST(ThreadManager, ClearReentrant) {
732 std::unique_ptr<Thread> t(Thread::Create());
733 EmptyHandler handler;
734 RefCountedHandler* inner_handler(
735 new rtc::RefCountedObject<RefCountedHandler>());
736 // When the empty handler is destroyed, it will clear messages queued for
737 // itself. The message to be cleared itself wraps a MessageHandler object
738 // (RefCountedHandler) so this will cause the message queue to be cleared
739 // again in a re-entrant fashion, which previously triggered a DCHECK.
740 // The inner handler will be removed in a re-entrant fashion from the
741 // message queue of the thread while the outer handler is removed, verifying
742 // that the iterator is not invalidated in "MessageQueue::Clear".
743 t->Post(RTC_FROM_HERE, inner_handler, 0);
744 t->Post(RTC_FROM_HERE, &handler, 0,
745 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
746}
747
Tommi9ebe6d72021-11-16 16:07:34 +0100748class DEPRECATED_AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749 public:
750 void IntCallback(int value) {
751 EXPECT_EQ(expected_thread_, Thread::Current());
752 int_value_ = value;
753 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 void SetExpectedThreadForIntCallback(Thread* thread) {
755 expected_thread_ = thread;
756 }
757
758 protected:
759 enum { kWaitTimeout = 1000 };
Tommi9ebe6d72021-11-16 16:07:34 +0100760 DEPRECATED_AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761
Niels Möller83830f32022-05-20 09:12:57 +0200762 rtc::AutoThread main_thread_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000763 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000764 Thread* expected_thread_;
765};
766
Tommi9ebe6d72021-11-16 16:07:34 +0100767TEST_F(DEPRECATED_AsyncInvokeTest, FireAndForget) {
Niels Möller0694ce72021-05-03 16:03:22 +0200768 DEPRECATED_AsyncInvoker invoker;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700770 auto thread = Thread::CreateWithSocketServer();
771 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000772 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800773 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700774 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800775 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700776 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000777}
778
Tommi9ebe6d72021-11-16 16:07:34 +0100779TEST_F(DEPRECATED_AsyncInvokeTest, NonCopyableFunctor) {
Niels Möller0694ce72021-05-03 16:03:22 +0200780 DEPRECATED_AsyncInvoker invoker;
Cameron Pickettd132ce12018-03-12 16:07:37 -0700781 // Create and start the thread.
782 auto thread = Thread::CreateWithSocketServer();
783 thread->Start();
784 // Try calling functor.
785 AtomicBool called;
786 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
787 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
788 thread->Stop();
789}
790
Tommi9ebe6d72021-11-16 16:07:34 +0100791TEST_F(DEPRECATED_AsyncInvokeTest, KillInvokerDuringExecute) {
deadbeef162cb532017-02-23 17:10:07 -0800792 // Use these events to get in a state where the functor is in the middle of
793 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
794 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100795 Event functor_started;
796 Event functor_continue;
797 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800798
tommie7251592017-07-14 14:44:46 -0700799 auto thread = Thread::CreateWithSocketServer();
800 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800801 volatile bool invoker_destroyed = false;
802 {
deadbeef3af63b02017-08-08 17:59:47 -0700803 auto functor = [&functor_started, &functor_continue, &functor_finished,
804 &invoker_destroyed] {
805 functor_started.Set();
806 functor_continue.Wait(Event::kForever);
807 rtc::Thread::Current()->SleepMs(kWaitTimeout);
808 EXPECT_FALSE(invoker_destroyed);
809 functor_finished.Set();
810 };
Niels Möller0694ce72021-05-03 16:03:22 +0200811 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700812 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800813 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700814
deadbeef3af63b02017-08-08 17:59:47 -0700815 // Destroy the invoker while the functor is still executing (doing
816 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700817 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800818 }
819
820 // If the destructor DIDN'T wait for the functor to finish executing, it will
821 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
822 // second.
823 invoker_destroyed = true;
824 functor_finished.Wait(Event::kForever);
825}
826
deadbeef3af63b02017-08-08 17:59:47 -0700827// Variant of the above test where the async-invoked task calls AsyncInvoke
Tommi9ebe6d72021-11-16 16:07:34 +0100828// *again*, for the thread on which the invoker is currently being destroyed.
829// This shouldn't deadlock or crash. The second invocation should be ignored.
830TEST_F(DEPRECATED_AsyncInvokeTest,
831 KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100832 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700833 // Flag used to verify that the recursively invoked task never actually runs.
834 bool reentrant_functor_run = false;
835
836 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200837 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700838 thread.Start();
839 {
Niels Möller0694ce72021-05-03 16:03:22 +0200840 DEPRECATED_AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700841 auto reentrant_functor = [&reentrant_functor_run] {
842 reentrant_functor_run = true;
843 };
844 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
845 functor_started.Set();
846 Thread::Current()->SleepMs(kWaitTimeout);
847 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
848 };
Artem Titov96e3b992021-07-26 16:03:14 +0200849 // This queues a task on `thread` to sleep for `kWaitTimeout` then queue a
850 // task on `main`. But this second queued task should never run, since the
deadbeef3af63b02017-08-08 17:59:47 -0700851 // destructor will be entered before it's even invoked.
852 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
853 functor_started.Wait(Event::kForever);
854 }
855 EXPECT_FALSE(reentrant_functor_run);
856}
857
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100858void WaitAndSetEvent(Event* wait_event, Event* set_event) {
859 wait_event->Wait(Event::kForever);
860 set_event->Set();
861}
862
863// A functor that keeps track of the number of copies and moves.
864class LifeCycleFunctor {
865 public:
866 struct Stats {
867 size_t copy_count = 0;
868 size_t move_count = 0;
869 };
870
871 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
872 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
873 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
874
875 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
876 stats_ = other.stats_;
877 event_ = other.event_;
878 ++stats_->copy_count;
879 return *this;
880 }
881
882 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
883 stats_ = other.stats_;
884 event_ = other.event_;
885 ++stats_->move_count;
886 return *this;
887 }
888
889 void operator()() { event_->Set(); }
890
891 private:
892 Stats* stats_;
893 Event* event_;
894};
895
896// A functor that verifies the thread it was destroyed on.
897class DestructionFunctor {
898 public:
899 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
900 : thread_(thread),
901 thread_was_current_(thread_was_current),
902 event_(event) {}
903 ~DestructionFunctor() {
904 // Only signal the event if this was the functor that was invoked to avoid
905 // the event being signaled due to the destruction of temporary/moved
906 // versions of this object.
907 if (was_invoked_) {
908 *thread_was_current_ = thread_->IsCurrent();
909 event_->Set();
910 }
911 }
912
913 void operator()() { was_invoked_ = true; }
914
915 private:
916 Thread* thread_;
917 bool* thread_was_current_;
918 Event* event_;
919 bool was_invoked_ = false;
920};
921
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100922TEST(ThreadPostTaskTest, InvokesWithLambda) {
923 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
924 background_thread->Start();
925
926 Event event;
Henrik Boström595f6882022-01-24 09:57:03 +0100927 background_thread->PostTask([&event] { event.Set(); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100928 event.Wait(Event::kForever);
929}
930
931TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
932 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
933 background_thread->Start();
934
935 LifeCycleFunctor::Stats stats;
936 Event event;
937 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100938 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100939 event.Wait(Event::kForever);
940
941 EXPECT_EQ(1u, stats.copy_count);
942 EXPECT_EQ(0u, stats.move_count);
943}
944
945TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
946 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
947 background_thread->Start();
948
949 LifeCycleFunctor::Stats stats;
950 Event event;
951 LifeCycleFunctor functor(&stats, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100952 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100953 event.Wait(Event::kForever);
954
955 EXPECT_EQ(0u, stats.copy_count);
956 EXPECT_EQ(1u, stats.move_count);
957}
958
959TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
960 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
961 background_thread->Start();
962
963 LifeCycleFunctor::Stats stats;
964 Event event;
965 LifeCycleFunctor functor(&stats, &event);
966 LifeCycleFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +0100967 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100968 event.Wait(Event::kForever);
969
970 EXPECT_EQ(1u, stats.copy_count);
971 EXPECT_EQ(0u, stats.move_count);
972}
973
974TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
975 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
976 background_thread->Start();
977
978 Event event;
979 bool was_invoked_on_background_thread = false;
980 DestructionFunctor functor(background_thread.get(),
981 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100982 background_thread->PostTask(functor);
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100983 event.Wait(Event::kForever);
984
985 EXPECT_TRUE(was_invoked_on_background_thread);
986}
987
988TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
989 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
990 background_thread->Start();
991
992 Event event;
993 bool was_invoked_on_background_thread = false;
994 DestructionFunctor functor(background_thread.get(),
995 &was_invoked_on_background_thread, &event);
Henrik Boström595f6882022-01-24 09:57:03 +0100996 background_thread->PostTask(std::move(functor));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100997 event.Wait(Event::kForever);
998
999 EXPECT_TRUE(was_invoked_on_background_thread);
1000}
1001
1002TEST(ThreadPostTaskTest,
1003 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1004 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1005 background_thread->Start();
1006
1007 Event event;
1008 bool was_invoked_on_background_thread = false;
1009 DestructionFunctor functor(background_thread.get(),
1010 &was_invoked_on_background_thread, &event);
1011 DestructionFunctor& functor_ref = functor;
Henrik Boström595f6882022-01-24 09:57:03 +01001012 background_thread->PostTask(functor_ref);
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001013 event.Wait(Event::kForever);
1014
1015 EXPECT_TRUE(was_invoked_on_background_thread);
1016}
1017
1018TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1019 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1020 background_thread->Start();
1021
1022 Event event;
1023 bool was_invoked_on_background_thread = false;
Niels Möller1a29a5d2021-01-18 11:35:23 +01001024 Thread* background_thread_ptr = background_thread.get();
Henrik Boström595f6882022-01-24 09:57:03 +01001025 background_thread->PostTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001026 [background_thread_ptr, &was_invoked_on_background_thread, &event] {
1027 was_invoked_on_background_thread = background_thread_ptr->IsCurrent();
1028 event.Set();
1029 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001030 event.Wait(Event::kForever);
1031
1032 EXPECT_TRUE(was_invoked_on_background_thread);
1033}
1034
1035TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1036 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1037 background_thread->Start();
1038
1039 // The first event ensures that SendSingleMessage() is not blocking this
1040 // thread. The second event ensures that the message is processed.
1041 Event event_set_by_test_thread;
1042 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001043 background_thread->PostTask(
Henrik Boström2deee4b2022-01-20 11:58:05 +01001044 [&event_set_by_test_thread, &event_set_by_background_thread] {
1045 WaitAndSetEvent(&event_set_by_test_thread,
1046 &event_set_by_background_thread);
1047 });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001048 event_set_by_test_thread.Set();
1049 event_set_by_background_thread.Wait(Event::kForever);
1050}
1051
1052TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1053 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1054 background_thread->Start();
1055
1056 Event first;
1057 Event second;
1058 Event third;
1059 Event fourth;
1060
Henrik Boström595f6882022-01-24 09:57:03 +01001061 background_thread->PostTask(
1062 [&first, &second] { WaitAndSetEvent(&first, &second); });
1063 background_thread->PostTask(
1064 [&second, &third] { WaitAndSetEvent(&second, &third); });
1065 background_thread->PostTask(
1066 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); });
Henrik Boströmba4dcc32019-02-28 09:34:06 +01001067
1068 // All tasks have been posted before the first one is unblocked.
1069 first.Set();
1070 // Only if the chain is invoked in posted order will the last event be set.
1071 fourth.Wait(Event::kForever);
1072}
1073
Steve Antonbcc1a762019-12-11 11:21:53 -08001074TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1075 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1076 background_thread->Start();
1077
1078 // The first event ensures that SendSingleMessage() is not blocking this
1079 // thread. The second event ensures that the message is processed.
1080 Event event_set_by_test_thread;
1081 Event event_set_by_background_thread;
Henrik Boström595f6882022-01-24 09:57:03 +01001082 background_thread->PostDelayedTask(
Niels Möller1a29a5d2021-01-18 11:35:23 +01001083 [&event_set_by_test_thread, &event_set_by_background_thread] {
1084 WaitAndSetEvent(&event_set_by_test_thread,
1085 &event_set_by_background_thread);
1086 },
Steve Antonbcc1a762019-12-11 11:21:53 -08001087 /*milliseconds=*/10);
1088 event_set_by_test_thread.Set();
1089 event_set_by_background_thread.Wait(Event::kForever);
1090}
1091
1092TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001093 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001094 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1095 background_thread->Start();
1096
1097 Event first;
1098 Event second;
1099 Event third;
1100 Event fourth;
1101
Henrik Boström595f6882022-01-24 09:57:03 +01001102 background_thread->PostDelayedTask(
1103 [&third, &fourth] { WaitAndSetEvent(&third, &fourth); },
Niels Möller1a29a5d2021-01-18 11:35:23 +01001104 /*milliseconds=*/11);
Henrik Boström595f6882022-01-24 09:57:03 +01001105 background_thread->PostDelayedTask(
1106 [&first, &second] { WaitAndSetEvent(&first, &second); },
Niels Möller1a29a5d2021-01-18 11:35:23 +01001107 /*milliseconds=*/9);
Henrik Boström595f6882022-01-24 09:57:03 +01001108 background_thread->PostDelayedTask(
1109 [&second, &third] { WaitAndSetEvent(&second, &third); },
Niels Möller1a29a5d2021-01-18 11:35:23 +01001110 /*milliseconds=*/10);
Steve Antonbcc1a762019-12-11 11:21:53 -08001111
1112 // All tasks have been posted before the first one is unblocked.
1113 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001114 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001115 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001116 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001117}
1118
Tommi6866dc72020-05-15 10:11:56 +02001119TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1120 auto current_tq = webrtc::TaskQueueBase::Current();
1121 {
1122 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1123 thread->WrapCurrent();
1124 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1125 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1126 thread->UnwrapCurrent();
1127 }
1128 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1129}
1130
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001131class ThreadFactory : public webrtc::TaskQueueFactory {
1132 public:
1133 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1134 CreateTaskQueue(absl::string_view /* name */,
1135 Priority /*priority*/) const override {
1136 std::unique_ptr<Thread> thread = Thread::Create();
1137 thread->Start();
1138 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1139 thread.release());
1140 }
1141};
1142
1143using ::webrtc::TaskQueueTest;
1144
1145INSTANTIATE_TEST_SUITE_P(RtcThread,
1146 TaskQueueTest,
1147 ::testing::Values(std::make_unique<ThreadFactory>));
1148
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001149} // namespace
1150} // namespace rtc