blob: 705e268c702a10d5534bdf95c2351e8a02347bb7 [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"
Steve Anton10542f22019-01-11 09:11:00 -080017#include "rtc_base/async_invoker.h"
18#include "rtc_base/async_udp_socket.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010019#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/event.h"
21#include "rtc_base/gunit.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010022#include "rtc_base/internal/default_socket_server.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "rtc_base/null_socket_server.h"
24#include "rtc_base/physical_socket_server.h"
25#include "rtc_base/socket_address.h"
Markus Handell4ab7dde2020-07-10 13:23:25 +020026#include "rtc_base/synchronization/mutex.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010027#include "rtc_base/task_utils/to_queued_task.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
Sebastian Jansson73387822020-01-16 11:15:35 +010039using ::webrtc::ToQueuedTask;
40
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:
Yves Gerey665174f2018-06-19 15:03:05 +020066 SocketClient(AsyncSocket* socket,
67 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;
206 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200207 void operator()() {
208 if (flag_)
209 *flag_ = true;
210 }
211
Cameron Pickettd132ce12018-03-12 16:07:37 -0700212 private:
213 AtomicBool* flag_;
214 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
215};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216
217// See: https://code.google.com/p/webrtc/issues/detail?id=2409
218TEST(ThreadTest, DISABLED_Main) {
219 const SocketAddress addr("127.0.0.1", 0);
220
221 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700222 auto th1 = Thread::CreateWithSocketServer();
223 Socket* socket =
224 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
225 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226
227 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700228 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700230 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
231 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232
233 socket->Connect(sock_client.address());
234
tommie7251592017-07-14 14:44:46 -0700235 th1->Start();
236 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700239 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240
241 // Give the clients a little while to run.
242 // Messages will be processed at 100, 300, 500, 700, 900.
243 Thread* th_main = Thread::Current();
244 th_main->ProcessMessages(1000);
245
246 // Stop the sending client. Give the receiver a bit longer to run, in case
247 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700248 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700250 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251
252 // Make sure the results were correct
253 EXPECT_EQ(5, msg_client.count);
254 EXPECT_EQ(34, msg_client.last);
255 EXPECT_EQ(5, sock_client.count);
256 EXPECT_EQ(55, sock_client.last);
257}
258
259// Test that setting thread names doesn't cause a malfunction.
260// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000261TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 // Default name
tommie7251592017-07-14 14:44:46 -0700263 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 EXPECT_TRUE(thread->Start());
265 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700267 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800268 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269 EXPECT_TRUE(thread->Start());
270 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 // Really long name
tommie7251592017-07-14 14:44:46 -0700272 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
274 EXPECT_TRUE(thread->Start());
275 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276}
277
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000278TEST(ThreadTest, Wrap) {
279 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200280 ThreadManager::Instance()->SetCurrentThread(nullptr);
281
282 {
283 CustomThread cthread;
284 EXPECT_TRUE(cthread.WrapCurrent());
285 EXPECT_EQ(&cthread, Thread::Current());
286 EXPECT_TRUE(cthread.RunningForTest());
287 EXPECT_FALSE(cthread.IsOwned());
288 cthread.UnwrapCurrent();
289 EXPECT_FALSE(cthread.RunningForTest());
290 }
291 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292}
293
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200294#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
295TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
296 // Create and start the thread.
297 auto thread1 = Thread::CreateWithSocketServer();
298 auto thread2 = Thread::CreateWithSocketServer();
299
300 thread1->PostTask(ToQueuedTask(
301 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
302 Thread* th_main = Thread::Current();
303 th_main->ProcessMessages(100);
304}
305
306TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
307 // Create and start the thread.
308 auto thread1 = Thread::CreateWithSocketServer();
309 auto thread2 = Thread::CreateWithSocketServer();
310 auto thread3 = Thread::CreateWithSocketServer();
311 auto thread4 = Thread::CreateWithSocketServer();
312
313 thread1->AllowInvokesToThread(thread2.get());
314 thread1->AllowInvokesToThread(thread3.get());
315
316 thread1->PostTask(ToQueuedTask([&]() {
317 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
318 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
319 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
320 }));
321 Thread* th_main = Thread::Current();
322 th_main->ProcessMessages(100);
323}
324
325TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
326 // Create and start the thread.
327 auto thread1 = Thread::CreateWithSocketServer();
328 auto thread2 = Thread::CreateWithSocketServer();
329
330 thread1->DisallowAllInvokes();
331
332 thread1->PostTask(ToQueuedTask([&]() {
333 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
334 }));
335 Thread* th_main = Thread::Current();
336 th_main->ProcessMessages(100);
337}
338#endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
339
340TEST(ThreadTest, InvokesAllowedByDefault) {
341 // Create and start the thread.
342 auto thread1 = Thread::CreateWithSocketServer();
343 auto thread2 = Thread::CreateWithSocketServer();
344
345 thread1->PostTask(ToQueuedTask(
346 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
347 Thread* th_main = Thread::Current();
348 th_main->ProcessMessages(100);
349}
350
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000351TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700353 auto thread = Thread::CreateWithSocketServer();
354 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700356 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800357 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700359 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800360 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361 // Try calling bare functions.
362 struct LocalFuncs {
363 static int Func1() { return 999; }
364 static void Func2() {}
365 };
tommie7251592017-07-14 14:44:46 -0700366 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
367 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368}
369
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000370// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100371// not deadlock but crash.
372#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
373TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
374 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000375 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100376 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700377 auto other_thread = Thread::CreateWithSocketServer();
378 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100379 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
380 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
381 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000382}
383
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100384TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
385 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
386 AutoThread thread;
387 Thread* first = Thread::Current();
388
389 auto second = Thread::Create();
390 second->Start();
391 auto third = Thread::Create();
392 third->Start();
393
394 second->Invoke<void>(RTC_FROM_HERE, [&] {
395 third->Invoke<void>(RTC_FROM_HERE, [&] {
396 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
397 });
398 });
399}
400
401#endif
402
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000403// Verifies that if thread A invokes a call on thread B and thread C is trying
404// to invoke A at the same time, thread A does not handle C's invoke while
405// invoking B.
406TEST(ThreadTest, ThreeThreadsInvoke) {
407 AutoThread thread;
408 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700409 auto thread_b = Thread::CreateWithSocketServer();
410 auto thread_c = Thread::CreateWithSocketServer();
411 thread_b->Start();
412 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000413
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000414 class LockedBool {
415 public:
416 explicit LockedBool(bool value) : value_(value) {}
417
418 void Set(bool value) {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200419 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000420 value_ = value;
421 }
422
423 bool Get() {
Markus Handell4ab7dde2020-07-10 13:23:25 +0200424 webrtc::MutexLock lock(&mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000425 return value_;
426 }
427
428 private:
Markus Handell4ab7dde2020-07-10 13:23:25 +0200429 webrtc::Mutex mutex_;
430 bool value_ RTC_GUARDED_BY(mutex_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000431 };
432
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000433 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000434 static void Set(LockedBool* out) { out->Set(true); }
435 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700436 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000437 }
438
439 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000440 static void SetAndInvokeSet(LockedBool* out,
441 Thread* thread,
442 LockedBool* out_inner) {
443 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000444 InvokeSet(thread, out_inner);
445 }
446
447 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
448 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800449 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
450 Thread* thread1,
451 Thread* thread2,
452 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000453 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000454
deadbeef162cb532017-02-23 17:10:07 -0800455 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700456 RTC_FROM_HERE, thread1,
457 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000458
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000459 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000460 }
461 };
462
deadbeef162cb532017-02-23 17:10:07 -0800463 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000464 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000465
466 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
467 // Thread B returns when C receives the call and C should be blocked until A
468 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700469 thread_b->Invoke<void>(RTC_FROM_HERE,
470 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
471 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000472 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000473
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000474 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000475}
476
jbauch25d1f282016-02-05 00:25:02 -0800477// Set the name on a thread when the underlying QueueDestroyed signal is
478// triggered. This causes an error if the object is already partially
479// destroyed.
480class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
481 public:
482 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
483 thread->SignalQueueDestroyed.connect(
484 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
485 }
486
487 void OnQueueDestroyed() {
488 // Makes sure that if we access the Thread while it's being destroyed, that
489 // it doesn't cause a problem because the vtable has been modified.
490 thread_->SetName("foo", nullptr);
491 }
492
493 private:
494 Thread* thread_;
495};
496
497TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700498 auto thread1 = Thread::CreateWithSocketServer();
499 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
500 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800501
502 Thread* thread2 = new AutoThread();
503 SetNameOnSignalQueueDestroyedTester tester2(thread2);
504 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800505}
506
Sebastian Jansson73387822020-01-16 11:15:35 +0100507class ThreadQueueTest : public ::testing::Test, public Thread {
508 public:
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100509 ThreadQueueTest() : Thread(CreateDefaultSocketServer(), true) {}
Sebastian Jansson73387822020-01-16 11:15:35 +0100510 bool IsLocked_Worker() {
511 if (!CritForTest()->TryEnter()) {
512 return true;
513 }
514 CritForTest()->Leave();
515 return false;
516 }
517 bool IsLocked() {
518 // We have to do this on a worker thread, or else the TryEnter will
519 // succeed, since our critical sections are reentrant.
520 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
521 worker->Start();
522 return worker->Invoke<bool>(
523 RTC_FROM_HERE, rtc::Bind(&ThreadQueueTest::IsLocked_Worker, this));
524 }
525};
526
527struct DeletedLockChecker {
528 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
529 : test(test), was_locked(was_locked), deleted(deleted) {}
530 ~DeletedLockChecker() {
531 *deleted = true;
532 *was_locked = test->IsLocked();
533 }
534 ThreadQueueTest* test;
535 bool* was_locked;
536 bool* deleted;
537};
538
539static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
540 EXPECT_TRUE(q != nullptr);
541 int64_t now = TimeMillis();
542 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
543 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
544 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
545 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
546 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
547
548 Message msg;
549 for (size_t i = 0; i < 5; ++i) {
550 memset(&msg, 0, sizeof(msg));
551 EXPECT_TRUE(q->Get(&msg, 0));
552 EXPECT_EQ(i, msg.message_id);
553 }
554
555 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
556}
557
558TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100559 Thread q(CreateDefaultSocketServer(), true);
Sebastian Jansson73387822020-01-16 11:15:35 +0100560 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
561
562 NullSocketServer nullss;
563 Thread q_nullss(&nullss, true);
564 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
565}
566
567TEST_F(ThreadQueueTest, DisposeNotLocked) {
568 bool was_locked = true;
569 bool deleted = false;
570 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
571 Dispose(d);
572 Message msg;
573 EXPECT_FALSE(Get(&msg, 0));
574 EXPECT_TRUE(deleted);
575 EXPECT_FALSE(was_locked);
576}
577
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200578class DeletedMessageHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100579 public:
580 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
581 ~DeletedMessageHandler() override { *deleted_ = true; }
582 void OnMessage(Message* msg) override {}
583
584 private:
585 bool* deleted_;
586};
587
588TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
589 bool deleted = false;
590 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
591 // First, post a dispose.
592 Dispose(handler);
593 // Now, post a message, which should *not* be returned by Get().
594 Post(RTC_FROM_HERE, handler, 1);
595 Message msg;
596 EXPECT_FALSE(Get(&msg, 0));
597 EXPECT_TRUE(deleted);
598}
599
600// Ensure that ProcessAllMessageQueues does its essential function; process
601// all messages (both delayed and non delayed) up until the current time, on
602// all registered message queues.
603TEST(ThreadManager, ProcessAllMessageQueues) {
604 Event entered_process_all_message_queues(true, false);
605 auto a = Thread::CreateWithSocketServer();
606 auto b = Thread::CreateWithSocketServer();
607 a->Start();
608 b->Start();
609
610 volatile int messages_processed = 0;
611 auto incrementer = [&messages_processed,
612 &entered_process_all_message_queues] {
613 // Wait for event as a means to ensure Increment doesn't occur outside
614 // of ProcessAllMessageQueues. The event is set by a message posted to
615 // the main thread, which is guaranteed to be handled inside
616 // ProcessAllMessageQueues.
617 entered_process_all_message_queues.Wait(Event::kForever);
618 AtomicOps::Increment(&messages_processed);
619 };
620 auto event_signaler = [&entered_process_all_message_queues] {
621 entered_process_all_message_queues.Set();
622 };
623
624 // Post messages (both delayed and non delayed) to both threads.
625 a->PostTask(ToQueuedTask(incrementer));
626 b->PostTask(ToQueuedTask(incrementer));
627 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
628 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
629 rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
630
631 ThreadManager::ProcessAllMessageQueuesForTesting();
632 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
633}
634
635// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
636TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
637 auto t = Thread::CreateWithSocketServer();
638 t->Start();
639 t->Quit();
640 ThreadManager::ProcessAllMessageQueuesForTesting();
641}
642
643// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
644// messages.
645TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
646 Event entered_process_all_message_queues(true, false);
647 auto t = Thread::CreateWithSocketServer();
648 t->Start();
649
650 auto clearer = [&entered_process_all_message_queues] {
651 // Wait for event as a means to ensure Clear doesn't occur outside of
652 // ProcessAllMessageQueues. The event is set by a message posted to the
653 // main thread, which is guaranteed to be handled inside
654 // ProcessAllMessageQueues.
655 entered_process_all_message_queues.Wait(Event::kForever);
656 rtc::Thread::Current()->Clear(nullptr);
657 };
658 auto event_signaler = [&entered_process_all_message_queues] {
659 entered_process_all_message_queues.Set();
660 };
661
662 // Post messages (both delayed and non delayed) to both threads.
663 t->PostTask(RTC_FROM_HERE, clearer);
664 rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
665 ThreadManager::ProcessAllMessageQueuesForTesting();
666}
667
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200668class RefCountedHandler : public MessageHandlerAutoCleanup,
669 public rtc::RefCountInterface {
Sebastian Jansson73387822020-01-16 11:15:35 +0100670 public:
671 void OnMessage(Message* msg) override {}
672};
673
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200674class EmptyHandler : public MessageHandlerAutoCleanup {
Sebastian Jansson73387822020-01-16 11:15:35 +0100675 public:
676 void OnMessage(Message* msg) override {}
677};
678
679TEST(ThreadManager, ClearReentrant) {
680 std::unique_ptr<Thread> t(Thread::Create());
681 EmptyHandler handler;
682 RefCountedHandler* inner_handler(
683 new rtc::RefCountedObject<RefCountedHandler>());
684 // When the empty handler is destroyed, it will clear messages queued for
685 // itself. The message to be cleared itself wraps a MessageHandler object
686 // (RefCountedHandler) so this will cause the message queue to be cleared
687 // again in a re-entrant fashion, which previously triggered a DCHECK.
688 // The inner handler will be removed in a re-entrant fashion from the
689 // message queue of the thread while the outer handler is removed, verifying
690 // that the iterator is not invalidated in "MessageQueue::Clear".
691 t->Post(RTC_FROM_HERE, inner_handler, 0);
692 t->Post(RTC_FROM_HERE, &handler, 0,
693 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
694}
695
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200696class AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000697 public:
698 void IntCallback(int value) {
699 EXPECT_EQ(expected_thread_, Thread::Current());
700 int_value_ = value;
701 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000702 void SetExpectedThreadForIntCallback(Thread* thread) {
703 expected_thread_ = thread;
704 }
705
706 protected:
707 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200708 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000709
710 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000711 Thread* expected_thread_;
712};
713
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000714TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000715 AsyncInvoker invoker;
716 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700717 auto thread = Thread::CreateWithSocketServer();
718 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000719 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800720 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700721 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800722 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700723 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000724}
725
Cameron Pickettd132ce12018-03-12 16:07:37 -0700726TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
727 AsyncInvoker invoker;
728 // Create and start the thread.
729 auto thread = Thread::CreateWithSocketServer();
730 thread->Start();
731 // Try calling functor.
732 AtomicBool called;
733 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
734 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
735 thread->Stop();
736}
737
deadbeef162cb532017-02-23 17:10:07 -0800738TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
739 // Use these events to get in a state where the functor is in the middle of
740 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
741 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100742 Event functor_started;
743 Event functor_continue;
744 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800745
tommie7251592017-07-14 14:44:46 -0700746 auto thread = Thread::CreateWithSocketServer();
747 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800748 volatile bool invoker_destroyed = false;
749 {
deadbeef3af63b02017-08-08 17:59:47 -0700750 auto functor = [&functor_started, &functor_continue, &functor_finished,
751 &invoker_destroyed] {
752 functor_started.Set();
753 functor_continue.Wait(Event::kForever);
754 rtc::Thread::Current()->SleepMs(kWaitTimeout);
755 EXPECT_FALSE(invoker_destroyed);
756 functor_finished.Set();
757 };
deadbeef162cb532017-02-23 17:10:07 -0800758 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700759 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800760 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700761
deadbeef3af63b02017-08-08 17:59:47 -0700762 // Destroy the invoker while the functor is still executing (doing
763 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700764 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800765 }
766
767 // If the destructor DIDN'T wait for the functor to finish executing, it will
768 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
769 // second.
770 invoker_destroyed = true;
771 functor_finished.Wait(Event::kForever);
772}
773
deadbeef3af63b02017-08-08 17:59:47 -0700774// Variant of the above test where the async-invoked task calls AsyncInvoke
775// *again*, for the thread on which the AsyncInvoker is currently being
776// destroyed. This shouldn't deadlock or crash; this second invocation should
777// just be ignored.
778TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100779 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700780 // Flag used to verify that the recursively invoked task never actually runs.
781 bool reentrant_functor_run = false;
782
783 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200784 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700785 thread.Start();
786 {
787 AsyncInvoker invoker;
788 auto reentrant_functor = [&reentrant_functor_run] {
789 reentrant_functor_run = true;
790 };
791 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
792 functor_started.Set();
793 Thread::Current()->SleepMs(kWaitTimeout);
794 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
795 };
796 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
797 // task on |main|. But this second queued task should never run, since the
798 // destructor will be entered before it's even invoked.
799 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
800 functor_started.Wait(Event::kForever);
801 }
802 EXPECT_FALSE(reentrant_functor_run);
803}
804
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000805TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000806 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800807 AtomicBool flag1;
808 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000809 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700810 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
811 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000812 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800813 EXPECT_FALSE(flag1.get());
814 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000815 // Force them to run now.
816 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800817 EXPECT_TRUE(flag1.get());
818 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819}
820
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000821TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000822 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800823 AtomicBool flag1;
824 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000825 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700826 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000827 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700828 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000829 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800830 EXPECT_FALSE(flag1.get());
831 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000832 // Execute pending calls with id == 5.
833 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800834 EXPECT_TRUE(flag1.get());
835 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000836 flag1 = false;
837 // Execute all pending calls. The id == 5 call should not execute again.
838 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800839 EXPECT_FALSE(flag1.get());
840 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000841}
842
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100843void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
844 *result = thread->IsCurrent();
845 event->Set();
846}
847
848void WaitAndSetEvent(Event* wait_event, Event* set_event) {
849 wait_event->Wait(Event::kForever);
850 set_event->Set();
851}
852
853// A functor that keeps track of the number of copies and moves.
854class LifeCycleFunctor {
855 public:
856 struct Stats {
857 size_t copy_count = 0;
858 size_t move_count = 0;
859 };
860
861 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
862 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
863 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
864
865 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
866 stats_ = other.stats_;
867 event_ = other.event_;
868 ++stats_->copy_count;
869 return *this;
870 }
871
872 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
873 stats_ = other.stats_;
874 event_ = other.event_;
875 ++stats_->move_count;
876 return *this;
877 }
878
879 void operator()() { event_->Set(); }
880
881 private:
882 Stats* stats_;
883 Event* event_;
884};
885
886// A functor that verifies the thread it was destroyed on.
887class DestructionFunctor {
888 public:
889 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
890 : thread_(thread),
891 thread_was_current_(thread_was_current),
892 event_(event) {}
893 ~DestructionFunctor() {
894 // Only signal the event if this was the functor that was invoked to avoid
895 // the event being signaled due to the destruction of temporary/moved
896 // versions of this object.
897 if (was_invoked_) {
898 *thread_was_current_ = thread_->IsCurrent();
899 event_->Set();
900 }
901 }
902
903 void operator()() { was_invoked_ = true; }
904
905 private:
906 Thread* thread_;
907 bool* thread_was_current_;
908 Event* event_;
909 bool was_invoked_ = false;
910};
911
912TEST(ThreadPostTaskTest, InvokesWithBind) {
913 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
914 background_thread->Start();
915
916 Event event;
917 background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
918 event.Wait(Event::kForever);
919}
920
921TEST(ThreadPostTaskTest, InvokesWithLambda) {
922 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
923 background_thread->Start();
924
925 Event event;
926 background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
927 event.Wait(Event::kForever);
928}
929
930TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
931 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
932 background_thread->Start();
933
934 LifeCycleFunctor::Stats stats;
935 Event event;
936 LifeCycleFunctor functor(&stats, &event);
937 background_thread->PostTask(RTC_FROM_HERE, functor);
938 event.Wait(Event::kForever);
939
940 EXPECT_EQ(1u, stats.copy_count);
941 EXPECT_EQ(0u, stats.move_count);
942}
943
944TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
945 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
946 background_thread->Start();
947
948 LifeCycleFunctor::Stats stats;
949 Event event;
950 LifeCycleFunctor functor(&stats, &event);
951 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
952 event.Wait(Event::kForever);
953
954 EXPECT_EQ(0u, stats.copy_count);
955 EXPECT_EQ(1u, stats.move_count);
956}
957
958TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
959 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
960 background_thread->Start();
961
962 LifeCycleFunctor::Stats stats;
963 Event event;
964 LifeCycleFunctor functor(&stats, &event);
965 LifeCycleFunctor& functor_ref = functor;
966 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
967 event.Wait(Event::kForever);
968
969 EXPECT_EQ(1u, stats.copy_count);
970 EXPECT_EQ(0u, stats.move_count);
971}
972
973TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
974 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
975 background_thread->Start();
976
977 Event event;
978 bool was_invoked_on_background_thread = false;
979 DestructionFunctor functor(background_thread.get(),
980 &was_invoked_on_background_thread, &event);
981 background_thread->PostTask(RTC_FROM_HERE, functor);
982 event.Wait(Event::kForever);
983
984 EXPECT_TRUE(was_invoked_on_background_thread);
985}
986
987TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
988 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
989 background_thread->Start();
990
991 Event event;
992 bool was_invoked_on_background_thread = false;
993 DestructionFunctor functor(background_thread.get(),
994 &was_invoked_on_background_thread, &event);
995 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
996 event.Wait(Event::kForever);
997
998 EXPECT_TRUE(was_invoked_on_background_thread);
999}
1000
1001TEST(ThreadPostTaskTest,
1002 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1003 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1004 background_thread->Start();
1005
1006 Event event;
1007 bool was_invoked_on_background_thread = false;
1008 DestructionFunctor functor(background_thread.get(),
1009 &was_invoked_on_background_thread, &event);
1010 DestructionFunctor& functor_ref = functor;
1011 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1012 event.Wait(Event::kForever);
1013
1014 EXPECT_TRUE(was_invoked_on_background_thread);
1015}
1016
1017TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1018 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1019 background_thread->Start();
1020
1021 Event event;
1022 bool was_invoked_on_background_thread = false;
1023 background_thread->PostTask(RTC_FROM_HERE,
1024 Bind(&ThreadIsCurrent, background_thread.get(),
1025 &was_invoked_on_background_thread, &event));
1026 event.Wait(Event::kForever);
1027
1028 EXPECT_TRUE(was_invoked_on_background_thread);
1029}
1030
1031TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1032 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1033 background_thread->Start();
1034
1035 // The first event ensures that SendSingleMessage() is not blocking this
1036 // thread. The second event ensures that the message is processed.
1037 Event event_set_by_test_thread;
1038 Event event_set_by_background_thread;
1039 background_thread->PostTask(RTC_FROM_HERE,
1040 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1041 &event_set_by_background_thread));
1042 event_set_by_test_thread.Set();
1043 event_set_by_background_thread.Wait(Event::kForever);
1044}
1045
1046TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1047 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1048 background_thread->Start();
1049
1050 Event first;
1051 Event second;
1052 Event third;
1053 Event fourth;
1054
1055 background_thread->PostTask(RTC_FROM_HERE,
1056 Bind(&WaitAndSetEvent, &first, &second));
1057 background_thread->PostTask(RTC_FROM_HERE,
1058 Bind(&WaitAndSetEvent, &second, &third));
1059 background_thread->PostTask(RTC_FROM_HERE,
1060 Bind(&WaitAndSetEvent, &third, &fourth));
1061
1062 // All tasks have been posted before the first one is unblocked.
1063 first.Set();
1064 // Only if the chain is invoked in posted order will the last event be set.
1065 fourth.Wait(Event::kForever);
1066}
1067
Steve Antonbcc1a762019-12-11 11:21:53 -08001068TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1069 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1070 background_thread->Start();
1071
1072 // The first event ensures that SendSingleMessage() is not blocking this
1073 // thread. The second event ensures that the message is processed.
1074 Event event_set_by_test_thread;
1075 Event event_set_by_background_thread;
1076 background_thread->PostDelayedTask(
1077 RTC_FROM_HERE,
1078 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1079 &event_set_by_background_thread),
1080 /*milliseconds=*/10);
1081 event_set_by_test_thread.Set();
1082 event_set_by_background_thread.Wait(Event::kForever);
1083}
1084
1085TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001086 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001087 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1088 background_thread->Start();
1089
1090 Event first;
1091 Event second;
1092 Event third;
1093 Event fourth;
1094
1095 background_thread->PostDelayedTask(RTC_FROM_HERE,
1096 Bind(&WaitAndSetEvent, &third, &fourth),
1097 /*milliseconds=*/11);
1098 background_thread->PostDelayedTask(RTC_FROM_HERE,
1099 Bind(&WaitAndSetEvent, &first, &second),
1100 /*milliseconds=*/9);
1101 background_thread->PostDelayedTask(RTC_FROM_HERE,
1102 Bind(&WaitAndSetEvent, &second, &third),
1103 /*milliseconds=*/10);
1104
1105 // All tasks have been posted before the first one is unblocked.
1106 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001107 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001108 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001109 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001110}
1111
Tommi6866dc72020-05-15 10:11:56 +02001112TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1113 auto current_tq = webrtc::TaskQueueBase::Current();
1114 {
1115 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1116 thread->WrapCurrent();
1117 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1118 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1119 thread->UnwrapCurrent();
1120 }
1121 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1122}
1123
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001124class ThreadFactory : public webrtc::TaskQueueFactory {
1125 public:
1126 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1127 CreateTaskQueue(absl::string_view /* name */,
1128 Priority /*priority*/) const override {
1129 std::unique_ptr<Thread> thread = Thread::Create();
1130 thread->Start();
1131 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1132 thread.release());
1133 }
1134};
1135
1136using ::webrtc::TaskQueueTest;
1137
1138INSTANTIATE_TEST_SUITE_P(RtcThread,
1139 TaskQueueTest,
1140 ::testing::Values(std::make_unique<ThreadFactory>));
1141
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001142} // namespace
1143} // namespace rtc