blob: bc0c3442ebc174ca741973b33670d4fc2f2d4b72 [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"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/null_socket_server.h"
23#include "rtc_base/physical_socket_server.h"
24#include "rtc_base/socket_address.h"
Sebastian Jansson73387822020-01-16 11:15:35 +010025#include "rtc_base/task_utils/to_queued_task.h"
Artem Titove41c4332018-07-25 15:04:28 +020026#include "rtc_base/third_party/sigslot/sigslot.h"
Sebastian Janssonda7267a2020-03-03 10:48:05 +010027#include "test/testsupport/rtc_expect_death.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028
29#if defined(WEBRTC_WIN)
30#include <comdef.h> // NOLINT
31#endif
32
Mirko Bonadeie10b1632018-12-11 18:43:40 +010033namespace rtc {
34namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035
Sebastian Jansson73387822020-01-16 11:15:35 +010036using ::webrtc::ToQueuedTask;
37
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038// Generates a sequence of numbers (collaboratively).
39class TestGenerator {
40 public:
41 TestGenerator() : last(0), count(0) {}
42
43 int Next(int prev) {
44 int result = prev + last;
45 last = result;
46 count += 1;
47 return result;
48 }
49
50 int last;
51 int count;
52};
53
54struct TestMessage : public MessageData {
55 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056
57 int value;
58};
59
60// Receives on a socket and sends by posting messages.
61class SocketClient : public TestGenerator, public sigslot::has_slots<> {
62 public:
Yves Gerey665174f2018-06-19 15:03:05 +020063 SocketClient(AsyncSocket* socket,
64 const SocketAddress& addr,
65 Thread* post_thread,
66 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067 : socket_(AsyncUDPSocket::Create(socket, addr)),
68 post_thread_(post_thread),
69 post_handler_(phandler) {
70 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
71 }
72
Steve Anton9de3aac2017-10-24 10:08:26 -070073 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074
75 SocketAddress address() const { return socket_->GetLocalAddress(); }
76
Yves Gerey665174f2018-06-19 15:03:05 +020077 void OnPacket(AsyncPacketSocket* socket,
78 const char* buf,
79 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010081 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020082 EXPECT_EQ(size, sizeof(uint32_t));
83 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
84 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070086 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
87 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088 }
89
90 private:
91 AsyncUDPSocket* socket_;
92 Thread* post_thread_;
93 MessageHandler* post_handler_;
94};
95
96// Receives messages and sends on a socket.
97class MessageClient : public MessageHandler, public TestGenerator {
98 public:
Yves Gerey665174f2018-06-19 15:03:05 +020099 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000100
Steve Anton9de3aac2017-10-24 10:08:26 -0700101 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102
Steve Anton9de3aac2017-10-24 10:08:26 -0700103 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
105 int result = Next(msg->value);
106 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
107 delete msg;
108 }
109
110 private:
111 Socket* socket_;
112};
113
deadbeefaea92932017-05-23 12:55:03 -0700114class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115 public:
tommie7251592017-07-14 14:44:46 -0700116 CustomThread()
117 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700118 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000120
Yves Gerey665174f2018-06-19 15:03:05 +0200121 bool WrapCurrent() { return Thread::WrapCurrent(); }
122 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123};
124
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125// A thread that does nothing when it runs and signals an event
126// when it is destroyed.
127class SignalWhenDestroyedThread : public Thread {
128 public:
129 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700130 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
131 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132
Steve Anton9de3aac2017-10-24 10:08:26 -0700133 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134 Stop();
135 event_->Set();
136 }
137
Steve Anton9de3aac2017-10-24 10:08:26 -0700138 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 // Do nothing.
140 }
141
142 private:
143 Event* event_;
144};
145
nissed9b75be2015-11-16 00:54:07 -0800146// A bool wrapped in a mutex, to avoid data races. Using a volatile
147// bool should be sufficient for correct code ("eventual consistency"
148// between caches is sufficient), but we can't tell the compiler about
149// that, and then tsan complains about a data race.
150
151// See also discussion at
152// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
153
154// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
155// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700156// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800157// performance critical, use a plain critical section for the time
158// being.
159
160class AtomicBool {
161 public:
162 explicit AtomicBool(bool value = false) : flag_(value) {}
163 AtomicBool& operator=(bool value) {
164 CritScope scoped_lock(&cs_);
165 flag_ = value;
166 return *this;
167 }
168 bool get() const {
169 CritScope scoped_lock(&cs_);
170 return flag_;
171 }
172
173 private:
pbos5ad935c2016-01-25 03:52:44 -0800174 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800175 bool flag_;
176};
177
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178// Function objects to test Thread::Invoke.
179struct FunctorA {
180 int operator()() { return 42; }
181};
182class FunctorB {
183 public:
nissed9b75be2015-11-16 00:54:07 -0800184 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200185 void operator()() {
186 if (flag_)
187 *flag_ = true;
188 }
189
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190 private:
nissed9b75be2015-11-16 00:54:07 -0800191 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192};
193struct FunctorC {
194 int operator()() {
195 Thread::Current()->ProcessMessages(50);
196 return 24;
197 }
198};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700199struct FunctorD {
200 public:
201 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
202 FunctorD(FunctorD&&) = default;
203 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200204 void operator()() {
205 if (flag_)
206 *flag_ = true;
207 }
208
Cameron Pickettd132ce12018-03-12 16:07:37 -0700209 private:
210 AtomicBool* flag_;
211 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
212};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213
214// See: https://code.google.com/p/webrtc/issues/detail?id=2409
215TEST(ThreadTest, DISABLED_Main) {
216 const SocketAddress addr("127.0.0.1", 0);
217
218 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700219 auto th1 = Thread::CreateWithSocketServer();
220 Socket* socket =
221 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
222 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223
224 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700225 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700227 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
228 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 socket->Connect(sock_client.address());
231
tommie7251592017-07-14 14:44:46 -0700232 th1->Start();
233 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234
235 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700236 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238 // Give the clients a little while to run.
239 // Messages will be processed at 100, 300, 500, 700, 900.
240 Thread* th_main = Thread::Current();
241 th_main->ProcessMessages(1000);
242
243 // Stop the sending client. Give the receiver a bit longer to run, in case
244 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700245 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700247 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248
249 // Make sure the results were correct
250 EXPECT_EQ(5, msg_client.count);
251 EXPECT_EQ(34, msg_client.last);
252 EXPECT_EQ(5, sock_client.count);
253 EXPECT_EQ(55, sock_client.last);
254}
255
256// Test that setting thread names doesn't cause a malfunction.
257// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000258TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259 // Default name
tommie7251592017-07-14 14:44:46 -0700260 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 EXPECT_TRUE(thread->Start());
262 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700264 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800265 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266 EXPECT_TRUE(thread->Start());
267 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268 // Really long name
tommie7251592017-07-14 14:44:46 -0700269 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
271 EXPECT_TRUE(thread->Start());
272 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273}
274
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000275TEST(ThreadTest, Wrap) {
276 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200277 ThreadManager::Instance()->SetCurrentThread(nullptr);
278
279 {
280 CustomThread cthread;
281 EXPECT_TRUE(cthread.WrapCurrent());
282 EXPECT_EQ(&cthread, Thread::Current());
283 EXPECT_TRUE(cthread.RunningForTest());
284 EXPECT_FALSE(cthread.IsOwned());
285 cthread.UnwrapCurrent();
286 EXPECT_FALSE(cthread.RunningForTest());
287 }
288 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289}
290
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200291#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
292TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
293 // Create and start the thread.
294 auto thread1 = Thread::CreateWithSocketServer();
295 auto thread2 = Thread::CreateWithSocketServer();
296
297 thread1->PostTask(ToQueuedTask(
298 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
299 Thread* th_main = Thread::Current();
300 th_main->ProcessMessages(100);
301}
302
303TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
304 // Create and start the thread.
305 auto thread1 = Thread::CreateWithSocketServer();
306 auto thread2 = Thread::CreateWithSocketServer();
307 auto thread3 = Thread::CreateWithSocketServer();
308 auto thread4 = Thread::CreateWithSocketServer();
309
310 thread1->AllowInvokesToThread(thread2.get());
311 thread1->AllowInvokesToThread(thread3.get());
312
313 thread1->PostTask(ToQueuedTask([&]() {
314 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get()));
315 EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
316 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
317 }));
318 Thread* th_main = Thread::Current();
319 th_main->ProcessMessages(100);
320}
321
322TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
323 // Create and start the thread.
324 auto thread1 = Thread::CreateWithSocketServer();
325 auto thread2 = Thread::CreateWithSocketServer();
326
327 thread1->DisallowAllInvokes();
328
329 thread1->PostTask(ToQueuedTask([&]() {
330 EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
331 }));
332 Thread* th_main = Thread::Current();
333 th_main->ProcessMessages(100);
334}
335#endif // (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
336
337TEST(ThreadTest, InvokesAllowedByDefault) {
338 // Create and start the thread.
339 auto thread1 = Thread::CreateWithSocketServer();
340 auto thread2 = Thread::CreateWithSocketServer();
341
342 thread1->PostTask(ToQueuedTask(
343 [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
344 Thread* th_main = Thread::Current();
345 th_main->ProcessMessages(100);
346}
347
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000348TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700350 auto thread = Thread::CreateWithSocketServer();
351 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700353 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800354 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700356 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800357 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358 // Try calling bare functions.
359 struct LocalFuncs {
360 static int Func1() { return 999; }
361 static void Func2() {}
362 };
tommie7251592017-07-14 14:44:46 -0700363 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
364 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365}
366
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000367// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100368// not deadlock but crash.
369#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
370TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
371 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000372 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100373 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700374 auto other_thread = Thread::CreateWithSocketServer();
375 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100376 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
377 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
378 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000379}
380
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100381TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
382 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
383 AutoThread thread;
384 Thread* first = Thread::Current();
385
386 auto second = Thread::Create();
387 second->Start();
388 auto third = Thread::Create();
389 third->Start();
390
391 second->Invoke<void>(RTC_FROM_HERE, [&] {
392 third->Invoke<void>(RTC_FROM_HERE, [&] {
393 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
394 });
395 });
396}
397
398#endif
399
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000400// Verifies that if thread A invokes a call on thread B and thread C is trying
401// to invoke A at the same time, thread A does not handle C's invoke while
402// invoking B.
403TEST(ThreadTest, ThreeThreadsInvoke) {
404 AutoThread thread;
405 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700406 auto thread_b = Thread::CreateWithSocketServer();
407 auto thread_c = Thread::CreateWithSocketServer();
408 thread_b->Start();
409 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000410
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000411 class LockedBool {
412 public:
413 explicit LockedBool(bool value) : value_(value) {}
414
415 void Set(bool value) {
416 CritScope lock(&crit_);
417 value_ = value;
418 }
419
420 bool Get() {
421 CritScope lock(&crit_);
422 return value_;
423 }
424
425 private:
426 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700427 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000428 };
429
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000430 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000431 static void Set(LockedBool* out) { out->Set(true); }
432 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700433 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000434 }
435
436 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000437 static void SetAndInvokeSet(LockedBool* out,
438 Thread* thread,
439 LockedBool* out_inner) {
440 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000441 InvokeSet(thread, out_inner);
442 }
443
444 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
445 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800446 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
447 Thread* thread1,
448 Thread* thread2,
449 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000450 CriticalSection crit;
451 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000452
deadbeef162cb532017-02-23 17:10:07 -0800453 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700454 RTC_FROM_HERE, thread1,
455 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000456
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000457 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000458 }
459 };
460
deadbeef162cb532017-02-23 17:10:07 -0800461 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000462 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000463
464 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
465 // Thread B returns when C receives the call and C should be blocked until A
466 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700467 thread_b->Invoke<void>(RTC_FROM_HERE,
468 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
469 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000470 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000471
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000472 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000473}
474
jbauch25d1f282016-02-05 00:25:02 -0800475// Set the name on a thread when the underlying QueueDestroyed signal is
476// triggered. This causes an error if the object is already partially
477// destroyed.
478class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
479 public:
480 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
481 thread->SignalQueueDestroyed.connect(
482 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
483 }
484
485 void OnQueueDestroyed() {
486 // Makes sure that if we access the Thread while it's being destroyed, that
487 // it doesn't cause a problem because the vtable has been modified.
488 thread_->SetName("foo", nullptr);
489 }
490
491 private:
492 Thread* thread_;
493};
494
495TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700496 auto thread1 = Thread::CreateWithSocketServer();
497 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
498 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800499
500 Thread* thread2 = new AutoThread();
501 SetNameOnSignalQueueDestroyedTester tester2(thread2);
502 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800503}
504
Sebastian Jansson73387822020-01-16 11:15:35 +0100505class ThreadQueueTest : public ::testing::Test, public Thread {
506 public:
507 ThreadQueueTest() : Thread(SocketServer::CreateDefault(), true) {}
508 bool IsLocked_Worker() {
509 if (!CritForTest()->TryEnter()) {
510 return true;
511 }
512 CritForTest()->Leave();
513 return false;
514 }
515 bool IsLocked() {
516 // We have to do this on a worker thread, or else the TryEnter will
517 // succeed, since our critical sections are reentrant.
518 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
519 worker->Start();
520 return worker->Invoke<bool>(
521 RTC_FROM_HERE, rtc::Bind(&ThreadQueueTest::IsLocked_Worker, this));
522 }
523};
524
525struct DeletedLockChecker {
526 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
527 : test(test), was_locked(was_locked), deleted(deleted) {}
528 ~DeletedLockChecker() {
529 *deleted = true;
530 *was_locked = test->IsLocked();
531 }
532 ThreadQueueTest* test;
533 bool* was_locked;
534 bool* deleted;
535};
536
537static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
538 EXPECT_TRUE(q != nullptr);
539 int64_t now = TimeMillis();
540 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
541 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
542 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
543 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
544 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
545
546 Message msg;
547 for (size_t i = 0; i < 5; ++i) {
548 memset(&msg, 0, sizeof(msg));
549 EXPECT_TRUE(q->Get(&msg, 0));
550 EXPECT_EQ(i, msg.message_id);
551 }
552
553 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
554}
555
556TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
557 Thread q(SocketServer::CreateDefault(), true);
558 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
559
560 NullSocketServer nullss;
561 Thread q_nullss(&nullss, true);
562 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
563}
564
565TEST_F(ThreadQueueTest, DisposeNotLocked) {
566 bool was_locked = true;
567 bool deleted = false;
568 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
569 Dispose(d);
570 Message msg;
571 EXPECT_FALSE(Get(&msg, 0));
572 EXPECT_TRUE(deleted);
573 EXPECT_FALSE(was_locked);
574}
575
576class DeletedMessageHandler : public MessageHandler {
577 public:
578 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
579 ~DeletedMessageHandler() override { *deleted_ = true; }
580 void OnMessage(Message* msg) override {}
581
582 private:
583 bool* deleted_;
584};
585
586TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
587 bool deleted = false;
588 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
589 // First, post a dispose.
590 Dispose(handler);
591 // Now, post a message, which should *not* be returned by Get().
592 Post(RTC_FROM_HERE, handler, 1);
593 Message msg;
594 EXPECT_FALSE(Get(&msg, 0));
595 EXPECT_TRUE(deleted);
596}
597
598// Ensure that ProcessAllMessageQueues does its essential function; process
599// all messages (both delayed and non delayed) up until the current time, on
600// all registered message queues.
601TEST(ThreadManager, ProcessAllMessageQueues) {
602 Event entered_process_all_message_queues(true, false);
603 auto a = Thread::CreateWithSocketServer();
604 auto b = Thread::CreateWithSocketServer();
605 a->Start();
606 b->Start();
607
608 volatile int messages_processed = 0;
609 auto incrementer = [&messages_processed,
610 &entered_process_all_message_queues] {
611 // Wait for event as a means to ensure Increment doesn't occur outside
612 // of ProcessAllMessageQueues. The event is set by a message posted to
613 // the main thread, which is guaranteed to be handled inside
614 // ProcessAllMessageQueues.
615 entered_process_all_message_queues.Wait(Event::kForever);
616 AtomicOps::Increment(&messages_processed);
617 };
618 auto event_signaler = [&entered_process_all_message_queues] {
619 entered_process_all_message_queues.Set();
620 };
621
622 // Post messages (both delayed and non delayed) to both threads.
623 a->PostTask(ToQueuedTask(incrementer));
624 b->PostTask(ToQueuedTask(incrementer));
625 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
626 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
627 rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
628
629 ThreadManager::ProcessAllMessageQueuesForTesting();
630 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
631}
632
633// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
634TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
635 auto t = Thread::CreateWithSocketServer();
636 t->Start();
637 t->Quit();
638 ThreadManager::ProcessAllMessageQueuesForTesting();
639}
640
641// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
642// messages.
643TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
644 Event entered_process_all_message_queues(true, false);
645 auto t = Thread::CreateWithSocketServer();
646 t->Start();
647
648 auto clearer = [&entered_process_all_message_queues] {
649 // Wait for event as a means to ensure Clear doesn't occur outside of
650 // ProcessAllMessageQueues. The event is set by a message posted to the
651 // main thread, which is guaranteed to be handled inside
652 // ProcessAllMessageQueues.
653 entered_process_all_message_queues.Wait(Event::kForever);
654 rtc::Thread::Current()->Clear(nullptr);
655 };
656 auto event_signaler = [&entered_process_all_message_queues] {
657 entered_process_all_message_queues.Set();
658 };
659
660 // Post messages (both delayed and non delayed) to both threads.
661 t->PostTask(RTC_FROM_HERE, clearer);
662 rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
663 ThreadManager::ProcessAllMessageQueuesForTesting();
664}
665
666class RefCountedHandler : public MessageHandler, public rtc::RefCountInterface {
667 public:
668 void OnMessage(Message* msg) override {}
669};
670
671class EmptyHandler : public MessageHandler {
672 public:
673 void OnMessage(Message* msg) override {}
674};
675
676TEST(ThreadManager, ClearReentrant) {
677 std::unique_ptr<Thread> t(Thread::Create());
678 EmptyHandler handler;
679 RefCountedHandler* inner_handler(
680 new rtc::RefCountedObject<RefCountedHandler>());
681 // When the empty handler is destroyed, it will clear messages queued for
682 // itself. The message to be cleared itself wraps a MessageHandler object
683 // (RefCountedHandler) so this will cause the message queue to be cleared
684 // again in a re-entrant fashion, which previously triggered a DCHECK.
685 // The inner handler will be removed in a re-entrant fashion from the
686 // message queue of the thread while the outer handler is removed, verifying
687 // that the iterator is not invalidated in "MessageQueue::Clear".
688 t->Post(RTC_FROM_HERE, inner_handler, 0);
689 t->Post(RTC_FROM_HERE, &handler, 0,
690 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
691}
692
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200693class AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000694 public:
695 void IntCallback(int value) {
696 EXPECT_EQ(expected_thread_, Thread::Current());
697 int_value_ = value;
698 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000699 void SetExpectedThreadForIntCallback(Thread* thread) {
700 expected_thread_ = thread;
701 }
702
703 protected:
704 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200705 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000706
707 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000708 Thread* expected_thread_;
709};
710
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000711TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 AsyncInvoker invoker;
713 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700714 auto thread = Thread::CreateWithSocketServer();
715 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000716 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800717 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700718 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800719 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700720 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000721}
722
Cameron Pickettd132ce12018-03-12 16:07:37 -0700723TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
724 AsyncInvoker invoker;
725 // Create and start the thread.
726 auto thread = Thread::CreateWithSocketServer();
727 thread->Start();
728 // Try calling functor.
729 AtomicBool called;
730 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
731 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
732 thread->Stop();
733}
734
deadbeef162cb532017-02-23 17:10:07 -0800735TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
736 // Use these events to get in a state where the functor is in the middle of
737 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
738 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100739 Event functor_started;
740 Event functor_continue;
741 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800742
tommie7251592017-07-14 14:44:46 -0700743 auto thread = Thread::CreateWithSocketServer();
744 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800745 volatile bool invoker_destroyed = false;
746 {
deadbeef3af63b02017-08-08 17:59:47 -0700747 auto functor = [&functor_started, &functor_continue, &functor_finished,
748 &invoker_destroyed] {
749 functor_started.Set();
750 functor_continue.Wait(Event::kForever);
751 rtc::Thread::Current()->SleepMs(kWaitTimeout);
752 EXPECT_FALSE(invoker_destroyed);
753 functor_finished.Set();
754 };
deadbeef162cb532017-02-23 17:10:07 -0800755 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700756 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800757 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700758
deadbeef3af63b02017-08-08 17:59:47 -0700759 // Destroy the invoker while the functor is still executing (doing
760 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700761 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800762 }
763
764 // If the destructor DIDN'T wait for the functor to finish executing, it will
765 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
766 // second.
767 invoker_destroyed = true;
768 functor_finished.Wait(Event::kForever);
769}
770
deadbeef3af63b02017-08-08 17:59:47 -0700771// Variant of the above test where the async-invoked task calls AsyncInvoke
772// *again*, for the thread on which the AsyncInvoker is currently being
773// destroyed. This shouldn't deadlock or crash; this second invocation should
774// just be ignored.
775TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100776 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700777 // Flag used to verify that the recursively invoked task never actually runs.
778 bool reentrant_functor_run = false;
779
780 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200781 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700782 thread.Start();
783 {
784 AsyncInvoker invoker;
785 auto reentrant_functor = [&reentrant_functor_run] {
786 reentrant_functor_run = true;
787 };
788 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
789 functor_started.Set();
790 Thread::Current()->SleepMs(kWaitTimeout);
791 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
792 };
793 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
794 // task on |main|. But this second queued task should never run, since the
795 // destructor will be entered before it's even invoked.
796 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
797 functor_started.Wait(Event::kForever);
798 }
799 EXPECT_FALSE(reentrant_functor_run);
800}
801
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000802TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000803 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800804 AtomicBool flag1;
805 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000806 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700807 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
808 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000809 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800810 EXPECT_FALSE(flag1.get());
811 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000812 // Force them to run now.
813 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800814 EXPECT_TRUE(flag1.get());
815 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816}
817
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000818TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800820 AtomicBool flag1;
821 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000822 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700823 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000824 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700825 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000826 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800827 EXPECT_FALSE(flag1.get());
828 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000829 // Execute pending calls with id == 5.
830 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800831 EXPECT_TRUE(flag1.get());
832 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000833 flag1 = false;
834 // Execute all pending calls. The id == 5 call should not execute again.
835 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800836 EXPECT_FALSE(flag1.get());
837 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000838}
839
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100840void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
841 *result = thread->IsCurrent();
842 event->Set();
843}
844
845void WaitAndSetEvent(Event* wait_event, Event* set_event) {
846 wait_event->Wait(Event::kForever);
847 set_event->Set();
848}
849
850// A functor that keeps track of the number of copies and moves.
851class LifeCycleFunctor {
852 public:
853 struct Stats {
854 size_t copy_count = 0;
855 size_t move_count = 0;
856 };
857
858 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
859 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
860 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
861
862 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
863 stats_ = other.stats_;
864 event_ = other.event_;
865 ++stats_->copy_count;
866 return *this;
867 }
868
869 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
870 stats_ = other.stats_;
871 event_ = other.event_;
872 ++stats_->move_count;
873 return *this;
874 }
875
876 void operator()() { event_->Set(); }
877
878 private:
879 Stats* stats_;
880 Event* event_;
881};
882
883// A functor that verifies the thread it was destroyed on.
884class DestructionFunctor {
885 public:
886 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
887 : thread_(thread),
888 thread_was_current_(thread_was_current),
889 event_(event) {}
890 ~DestructionFunctor() {
891 // Only signal the event if this was the functor that was invoked to avoid
892 // the event being signaled due to the destruction of temporary/moved
893 // versions of this object.
894 if (was_invoked_) {
895 *thread_was_current_ = thread_->IsCurrent();
896 event_->Set();
897 }
898 }
899
900 void operator()() { was_invoked_ = true; }
901
902 private:
903 Thread* thread_;
904 bool* thread_was_current_;
905 Event* event_;
906 bool was_invoked_ = false;
907};
908
909TEST(ThreadPostTaskTest, InvokesWithBind) {
910 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
911 background_thread->Start();
912
913 Event event;
914 background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
915 event.Wait(Event::kForever);
916}
917
918TEST(ThreadPostTaskTest, InvokesWithLambda) {
919 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
920 background_thread->Start();
921
922 Event event;
923 background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
924 event.Wait(Event::kForever);
925}
926
927TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
928 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
929 background_thread->Start();
930
931 LifeCycleFunctor::Stats stats;
932 Event event;
933 LifeCycleFunctor functor(&stats, &event);
934 background_thread->PostTask(RTC_FROM_HERE, functor);
935 event.Wait(Event::kForever);
936
937 EXPECT_EQ(1u, stats.copy_count);
938 EXPECT_EQ(0u, stats.move_count);
939}
940
941TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
942 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
943 background_thread->Start();
944
945 LifeCycleFunctor::Stats stats;
946 Event event;
947 LifeCycleFunctor functor(&stats, &event);
948 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
949 event.Wait(Event::kForever);
950
951 EXPECT_EQ(0u, stats.copy_count);
952 EXPECT_EQ(1u, stats.move_count);
953}
954
955TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
956 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
957 background_thread->Start();
958
959 LifeCycleFunctor::Stats stats;
960 Event event;
961 LifeCycleFunctor functor(&stats, &event);
962 LifeCycleFunctor& functor_ref = functor;
963 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
964 event.Wait(Event::kForever);
965
966 EXPECT_EQ(1u, stats.copy_count);
967 EXPECT_EQ(0u, stats.move_count);
968}
969
970TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
971 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
972 background_thread->Start();
973
974 Event event;
975 bool was_invoked_on_background_thread = false;
976 DestructionFunctor functor(background_thread.get(),
977 &was_invoked_on_background_thread, &event);
978 background_thread->PostTask(RTC_FROM_HERE, functor);
979 event.Wait(Event::kForever);
980
981 EXPECT_TRUE(was_invoked_on_background_thread);
982}
983
984TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
985 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
986 background_thread->Start();
987
988 Event event;
989 bool was_invoked_on_background_thread = false;
990 DestructionFunctor functor(background_thread.get(),
991 &was_invoked_on_background_thread, &event);
992 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
993 event.Wait(Event::kForever);
994
995 EXPECT_TRUE(was_invoked_on_background_thread);
996}
997
998TEST(ThreadPostTaskTest,
999 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1000 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1001 background_thread->Start();
1002
1003 Event event;
1004 bool was_invoked_on_background_thread = false;
1005 DestructionFunctor functor(background_thread.get(),
1006 &was_invoked_on_background_thread, &event);
1007 DestructionFunctor& functor_ref = functor;
1008 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1009 event.Wait(Event::kForever);
1010
1011 EXPECT_TRUE(was_invoked_on_background_thread);
1012}
1013
1014TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1015 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1016 background_thread->Start();
1017
1018 Event event;
1019 bool was_invoked_on_background_thread = false;
1020 background_thread->PostTask(RTC_FROM_HERE,
1021 Bind(&ThreadIsCurrent, background_thread.get(),
1022 &was_invoked_on_background_thread, &event));
1023 event.Wait(Event::kForever);
1024
1025 EXPECT_TRUE(was_invoked_on_background_thread);
1026}
1027
1028TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1029 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1030 background_thread->Start();
1031
1032 // The first event ensures that SendSingleMessage() is not blocking this
1033 // thread. The second event ensures that the message is processed.
1034 Event event_set_by_test_thread;
1035 Event event_set_by_background_thread;
1036 background_thread->PostTask(RTC_FROM_HERE,
1037 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1038 &event_set_by_background_thread));
1039 event_set_by_test_thread.Set();
1040 event_set_by_background_thread.Wait(Event::kForever);
1041}
1042
1043TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1044 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1045 background_thread->Start();
1046
1047 Event first;
1048 Event second;
1049 Event third;
1050 Event fourth;
1051
1052 background_thread->PostTask(RTC_FROM_HERE,
1053 Bind(&WaitAndSetEvent, &first, &second));
1054 background_thread->PostTask(RTC_FROM_HERE,
1055 Bind(&WaitAndSetEvent, &second, &third));
1056 background_thread->PostTask(RTC_FROM_HERE,
1057 Bind(&WaitAndSetEvent, &third, &fourth));
1058
1059 // All tasks have been posted before the first one is unblocked.
1060 first.Set();
1061 // Only if the chain is invoked in posted order will the last event be set.
1062 fourth.Wait(Event::kForever);
1063}
1064
Steve Antonbcc1a762019-12-11 11:21:53 -08001065TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1066 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1067 background_thread->Start();
1068
1069 // The first event ensures that SendSingleMessage() is not blocking this
1070 // thread. The second event ensures that the message is processed.
1071 Event event_set_by_test_thread;
1072 Event event_set_by_background_thread;
1073 background_thread->PostDelayedTask(
1074 RTC_FROM_HERE,
1075 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1076 &event_set_by_background_thread),
1077 /*milliseconds=*/10);
1078 event_set_by_test_thread.Set();
1079 event_set_by_background_thread.Wait(Event::kForever);
1080}
1081
1082TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001083 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001084 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1085 background_thread->Start();
1086
1087 Event first;
1088 Event second;
1089 Event third;
1090 Event fourth;
1091
1092 background_thread->PostDelayedTask(RTC_FROM_HERE,
1093 Bind(&WaitAndSetEvent, &third, &fourth),
1094 /*milliseconds=*/11);
1095 background_thread->PostDelayedTask(RTC_FROM_HERE,
1096 Bind(&WaitAndSetEvent, &first, &second),
1097 /*milliseconds=*/9);
1098 background_thread->PostDelayedTask(RTC_FROM_HERE,
1099 Bind(&WaitAndSetEvent, &second, &third),
1100 /*milliseconds=*/10);
1101
1102 // All tasks have been posted before the first one is unblocked.
1103 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001104 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001105 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001106 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001107}
1108
Tommi6866dc72020-05-15 10:11:56 +02001109TEST(ThreadPostDelayedTaskTest, IsCurrentTaskQueue) {
1110 auto current_tq = webrtc::TaskQueueBase::Current();
1111 {
1112 std::unique_ptr<rtc::Thread> thread(rtc::Thread::Create());
1113 thread->WrapCurrent();
1114 EXPECT_EQ(webrtc::TaskQueueBase::Current(),
1115 static_cast<webrtc::TaskQueueBase*>(thread.get()));
1116 thread->UnwrapCurrent();
1117 }
1118 EXPECT_EQ(webrtc::TaskQueueBase::Current(), current_tq);
1119}
1120
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001121class ThreadFactory : public webrtc::TaskQueueFactory {
1122 public:
1123 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1124 CreateTaskQueue(absl::string_view /* name */,
1125 Priority /*priority*/) const override {
1126 std::unique_ptr<Thread> thread = Thread::Create();
1127 thread->Start();
1128 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1129 thread.release());
1130 }
1131};
1132
1133using ::webrtc::TaskQueueTest;
1134
1135INSTANTIATE_TEST_SUITE_P(RtcThread,
1136 TaskQueueTest,
1137 ::testing::Values(std::make_unique<ThreadFactory>));
1138
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001139} // namespace
1140} // namespace rtc