blob: 91bea4f9b3e423439dd4b9394f390421b076c1d3 [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
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000291TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700293 auto thread = Thread::CreateWithSocketServer();
294 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700296 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800297 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700299 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800300 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 // Try calling bare functions.
302 struct LocalFuncs {
303 static int Func1() { return 999; }
304 static void Func2() {}
305 };
tommie7251592017-07-14 14:44:46 -0700306 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
307 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308}
309
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000310// Verifies that two threads calling Invoke on each other at the same time does
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100311// not deadlock but crash.
312#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID)
313TEST(ThreadTest, TwoThreadsInvokeDeathTest) {
314 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000315 AutoThread thread;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100316 Thread* main_thread = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700317 auto other_thread = Thread::CreateWithSocketServer();
318 other_thread->Start();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100319 other_thread->Invoke<void>(RTC_FROM_HERE, [main_thread] {
320 RTC_EXPECT_DEATH(main_thread->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
321 });
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000322}
323
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100324TEST(ThreadTest, ThreeThreadsInvokeDeathTest) {
325 ::testing::GTEST_FLAG(death_test_style) = "threadsafe";
326 AutoThread thread;
327 Thread* first = Thread::Current();
328
329 auto second = Thread::Create();
330 second->Start();
331 auto third = Thread::Create();
332 third->Start();
333
334 second->Invoke<void>(RTC_FROM_HERE, [&] {
335 third->Invoke<void>(RTC_FROM_HERE, [&] {
336 RTC_EXPECT_DEATH(first->Invoke<void>(RTC_FROM_HERE, [] {}), "loop");
337 });
338 });
339}
340
341#endif
342
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000343// Verifies that if thread A invokes a call on thread B and thread C is trying
344// to invoke A at the same time, thread A does not handle C's invoke while
345// invoking B.
346TEST(ThreadTest, ThreeThreadsInvoke) {
347 AutoThread thread;
348 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700349 auto thread_b = Thread::CreateWithSocketServer();
350 auto thread_c = Thread::CreateWithSocketServer();
351 thread_b->Start();
352 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000353
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000354 class LockedBool {
355 public:
356 explicit LockedBool(bool value) : value_(value) {}
357
358 void Set(bool value) {
359 CritScope lock(&crit_);
360 value_ = value;
361 }
362
363 bool Get() {
364 CritScope lock(&crit_);
365 return value_;
366 }
367
368 private:
369 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700370 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000371 };
372
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000373 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000374 static void Set(LockedBool* out) { out->Set(true); }
375 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700376 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000377 }
378
379 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000380 static void SetAndInvokeSet(LockedBool* out,
381 Thread* thread,
382 LockedBool* out_inner) {
383 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000384 InvokeSet(thread, out_inner);
385 }
386
387 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
388 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800389 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
390 Thread* thread1,
391 Thread* thread2,
392 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000393 CriticalSection crit;
394 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000395
deadbeef162cb532017-02-23 17:10:07 -0800396 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700397 RTC_FROM_HERE, thread1,
398 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000399
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000400 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000401 }
402 };
403
deadbeef162cb532017-02-23 17:10:07 -0800404 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000405 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000406
407 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
408 // Thread B returns when C receives the call and C should be blocked until A
409 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700410 thread_b->Invoke<void>(RTC_FROM_HERE,
411 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
412 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000413 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000414
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000415 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000416}
417
jbauch25d1f282016-02-05 00:25:02 -0800418// Set the name on a thread when the underlying QueueDestroyed signal is
419// triggered. This causes an error if the object is already partially
420// destroyed.
421class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
422 public:
423 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
424 thread->SignalQueueDestroyed.connect(
425 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
426 }
427
428 void OnQueueDestroyed() {
429 // Makes sure that if we access the Thread while it's being destroyed, that
430 // it doesn't cause a problem because the vtable has been modified.
431 thread_->SetName("foo", nullptr);
432 }
433
434 private:
435 Thread* thread_;
436};
437
438TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700439 auto thread1 = Thread::CreateWithSocketServer();
440 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
441 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800442
443 Thread* thread2 = new AutoThread();
444 SetNameOnSignalQueueDestroyedTester tester2(thread2);
445 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800446}
447
Sebastian Jansson73387822020-01-16 11:15:35 +0100448class ThreadQueueTest : public ::testing::Test, public Thread {
449 public:
450 ThreadQueueTest() : Thread(SocketServer::CreateDefault(), true) {}
451 bool IsLocked_Worker() {
452 if (!CritForTest()->TryEnter()) {
453 return true;
454 }
455 CritForTest()->Leave();
456 return false;
457 }
458 bool IsLocked() {
459 // We have to do this on a worker thread, or else the TryEnter will
460 // succeed, since our critical sections are reentrant.
461 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
462 worker->Start();
463 return worker->Invoke<bool>(
464 RTC_FROM_HERE, rtc::Bind(&ThreadQueueTest::IsLocked_Worker, this));
465 }
466};
467
468struct DeletedLockChecker {
469 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
470 : test(test), was_locked(was_locked), deleted(deleted) {}
471 ~DeletedLockChecker() {
472 *deleted = true;
473 *was_locked = test->IsLocked();
474 }
475 ThreadQueueTest* test;
476 bool* was_locked;
477 bool* deleted;
478};
479
480static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
481 EXPECT_TRUE(q != nullptr);
482 int64_t now = TimeMillis();
483 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
484 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
485 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
486 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
487 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
488
489 Message msg;
490 for (size_t i = 0; i < 5; ++i) {
491 memset(&msg, 0, sizeof(msg));
492 EXPECT_TRUE(q->Get(&msg, 0));
493 EXPECT_EQ(i, msg.message_id);
494 }
495
496 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
497}
498
499TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
500 Thread q(SocketServer::CreateDefault(), true);
501 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
502
503 NullSocketServer nullss;
504 Thread q_nullss(&nullss, true);
505 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
506}
507
508TEST_F(ThreadQueueTest, DisposeNotLocked) {
509 bool was_locked = true;
510 bool deleted = false;
511 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
512 Dispose(d);
513 Message msg;
514 EXPECT_FALSE(Get(&msg, 0));
515 EXPECT_TRUE(deleted);
516 EXPECT_FALSE(was_locked);
517}
518
519class DeletedMessageHandler : public MessageHandler {
520 public:
521 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
522 ~DeletedMessageHandler() override { *deleted_ = true; }
523 void OnMessage(Message* msg) override {}
524
525 private:
526 bool* deleted_;
527};
528
529TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
530 bool deleted = false;
531 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
532 // First, post a dispose.
533 Dispose(handler);
534 // Now, post a message, which should *not* be returned by Get().
535 Post(RTC_FROM_HERE, handler, 1);
536 Message msg;
537 EXPECT_FALSE(Get(&msg, 0));
538 EXPECT_TRUE(deleted);
539}
540
541// Ensure that ProcessAllMessageQueues does its essential function; process
542// all messages (both delayed and non delayed) up until the current time, on
543// all registered message queues.
544TEST(ThreadManager, ProcessAllMessageQueues) {
545 Event entered_process_all_message_queues(true, false);
546 auto a = Thread::CreateWithSocketServer();
547 auto b = Thread::CreateWithSocketServer();
548 a->Start();
549 b->Start();
550
551 volatile int messages_processed = 0;
552 auto incrementer = [&messages_processed,
553 &entered_process_all_message_queues] {
554 // Wait for event as a means to ensure Increment doesn't occur outside
555 // of ProcessAllMessageQueues. The event is set by a message posted to
556 // the main thread, which is guaranteed to be handled inside
557 // ProcessAllMessageQueues.
558 entered_process_all_message_queues.Wait(Event::kForever);
559 AtomicOps::Increment(&messages_processed);
560 };
561 auto event_signaler = [&entered_process_all_message_queues] {
562 entered_process_all_message_queues.Set();
563 };
564
565 // Post messages (both delayed and non delayed) to both threads.
566 a->PostTask(ToQueuedTask(incrementer));
567 b->PostTask(ToQueuedTask(incrementer));
568 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
569 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
570 rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
571
572 ThreadManager::ProcessAllMessageQueuesForTesting();
573 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
574}
575
576// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
577TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
578 auto t = Thread::CreateWithSocketServer();
579 t->Start();
580 t->Quit();
581 ThreadManager::ProcessAllMessageQueuesForTesting();
582}
583
584// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
585// messages.
586TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
587 Event entered_process_all_message_queues(true, false);
588 auto t = Thread::CreateWithSocketServer();
589 t->Start();
590
591 auto clearer = [&entered_process_all_message_queues] {
592 // Wait for event as a means to ensure Clear doesn't occur outside of
593 // ProcessAllMessageQueues. The event is set by a message posted to the
594 // main thread, which is guaranteed to be handled inside
595 // ProcessAllMessageQueues.
596 entered_process_all_message_queues.Wait(Event::kForever);
597 rtc::Thread::Current()->Clear(nullptr);
598 };
599 auto event_signaler = [&entered_process_all_message_queues] {
600 entered_process_all_message_queues.Set();
601 };
602
603 // Post messages (both delayed and non delayed) to both threads.
604 t->PostTask(RTC_FROM_HERE, clearer);
605 rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
606 ThreadManager::ProcessAllMessageQueuesForTesting();
607}
608
609class RefCountedHandler : public MessageHandler, public rtc::RefCountInterface {
610 public:
611 void OnMessage(Message* msg) override {}
612};
613
614class EmptyHandler : public MessageHandler {
615 public:
616 void OnMessage(Message* msg) override {}
617};
618
619TEST(ThreadManager, ClearReentrant) {
620 std::unique_ptr<Thread> t(Thread::Create());
621 EmptyHandler handler;
622 RefCountedHandler* inner_handler(
623 new rtc::RefCountedObject<RefCountedHandler>());
624 // When the empty handler is destroyed, it will clear messages queued for
625 // itself. The message to be cleared itself wraps a MessageHandler object
626 // (RefCountedHandler) so this will cause the message queue to be cleared
627 // again in a re-entrant fashion, which previously triggered a DCHECK.
628 // The inner handler will be removed in a re-entrant fashion from the
629 // message queue of the thread while the outer handler is removed, verifying
630 // that the iterator is not invalidated in "MessageQueue::Clear".
631 t->Post(RTC_FROM_HERE, inner_handler, 0);
632 t->Post(RTC_FROM_HERE, &handler, 0,
633 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
634}
635
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200636class AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000637 public:
638 void IntCallback(int value) {
639 EXPECT_EQ(expected_thread_, Thread::Current());
640 int_value_ = value;
641 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000642 void SetExpectedThreadForIntCallback(Thread* thread) {
643 expected_thread_ = thread;
644 }
645
646 protected:
647 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200648 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000649
650 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000651 Thread* expected_thread_;
652};
653
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000654TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000655 AsyncInvoker invoker;
656 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700657 auto thread = Thread::CreateWithSocketServer();
658 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000659 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800660 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700661 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800662 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700663 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000664}
665
Cameron Pickettd132ce12018-03-12 16:07:37 -0700666TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
667 AsyncInvoker invoker;
668 // Create and start the thread.
669 auto thread = Thread::CreateWithSocketServer();
670 thread->Start();
671 // Try calling functor.
672 AtomicBool called;
673 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
674 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
675 thread->Stop();
676}
677
deadbeef162cb532017-02-23 17:10:07 -0800678TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
679 // Use these events to get in a state where the functor is in the middle of
680 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
681 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100682 Event functor_started;
683 Event functor_continue;
684 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800685
tommie7251592017-07-14 14:44:46 -0700686 auto thread = Thread::CreateWithSocketServer();
687 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800688 volatile bool invoker_destroyed = false;
689 {
deadbeef3af63b02017-08-08 17:59:47 -0700690 auto functor = [&functor_started, &functor_continue, &functor_finished,
691 &invoker_destroyed] {
692 functor_started.Set();
693 functor_continue.Wait(Event::kForever);
694 rtc::Thread::Current()->SleepMs(kWaitTimeout);
695 EXPECT_FALSE(invoker_destroyed);
696 functor_finished.Set();
697 };
deadbeef162cb532017-02-23 17:10:07 -0800698 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700699 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800700 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700701
deadbeef3af63b02017-08-08 17:59:47 -0700702 // Destroy the invoker while the functor is still executing (doing
703 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700704 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800705 }
706
707 // If the destructor DIDN'T wait for the functor to finish executing, it will
708 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
709 // second.
710 invoker_destroyed = true;
711 functor_finished.Wait(Event::kForever);
712}
713
deadbeef3af63b02017-08-08 17:59:47 -0700714// Variant of the above test where the async-invoked task calls AsyncInvoke
715// *again*, for the thread on which the AsyncInvoker is currently being
716// destroyed. This shouldn't deadlock or crash; this second invocation should
717// just be ignored.
718TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100719 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700720 // Flag used to verify that the recursively invoked task never actually runs.
721 bool reentrant_functor_run = false;
722
723 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200724 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700725 thread.Start();
726 {
727 AsyncInvoker invoker;
728 auto reentrant_functor = [&reentrant_functor_run] {
729 reentrant_functor_run = true;
730 };
731 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
732 functor_started.Set();
733 Thread::Current()->SleepMs(kWaitTimeout);
734 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
735 };
736 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
737 // task on |main|. But this second queued task should never run, since the
738 // destructor will be entered before it's even invoked.
739 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
740 functor_started.Wait(Event::kForever);
741 }
742 EXPECT_FALSE(reentrant_functor_run);
743}
744
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000745TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000746 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800747 AtomicBool flag1;
748 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700750 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
751 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800753 EXPECT_FALSE(flag1.get());
754 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 // Force them to run now.
756 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800757 EXPECT_TRUE(flag1.get());
758 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759}
760
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000761TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800763 AtomicBool flag1;
764 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000765 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700766 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700768 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800770 EXPECT_FALSE(flag1.get());
771 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000772 // Execute pending calls with id == 5.
773 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800774 EXPECT_TRUE(flag1.get());
775 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000776 flag1 = false;
777 // Execute all pending calls. The id == 5 call should not execute again.
778 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800779 EXPECT_FALSE(flag1.get());
780 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781}
782
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200783class GuardedAsyncInvokeTest : public ::testing::Test {
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200784 public:
785 void IntCallback(int value) {
786 EXPECT_EQ(expected_thread_, Thread::Current());
787 int_value_ = value;
788 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200789 void SetExpectedThreadForIntCallback(Thread* thread) {
790 expected_thread_ = thread;
791 }
792
793 protected:
794 const static int kWaitTimeout = 1000;
Yves Gerey665174f2018-06-19 15:03:05 +0200795 GuardedAsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200796
797 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200798 Thread* expected_thread_;
799};
800
801// Functor for creating an invoker.
802struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700803 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
804 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200805 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700806 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200807};
808
809// Test that we can call AsyncInvoke<void>() after the thread died.
810TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
811 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700812 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200813 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700814 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200815 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700816 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200817 // Kill |thread|.
818 thread = nullptr;
819 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800820 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700821 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200822 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800823 WAIT(called.get(), kWaitTimeout);
824 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200825}
826
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200827// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
828// when Thread is still alive.
829TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
830 GuardedAsyncInvoker invoker;
831 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800832 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700833 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800834 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200835}
836
Cameron Pickettd132ce12018-03-12 16:07:37 -0700837TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
838 GuardedAsyncInvoker invoker;
839 // Try calling functor.
840 AtomicBool called;
841 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
842 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
843}
844
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200845TEST_F(GuardedAsyncInvokeTest, Flush) {
846 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800847 AtomicBool flag1;
848 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200849 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700850 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
851 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200852 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800853 EXPECT_FALSE(flag1.get());
854 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200855 // Force them to run now.
856 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800857 EXPECT_TRUE(flag1.get());
858 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200859}
860
861TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
862 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800863 AtomicBool flag1;
864 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200865 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700866 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
867 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200868 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800869 EXPECT_FALSE(flag1.get());
870 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200871 // Execute pending calls with id == 5.
872 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800873 EXPECT_TRUE(flag1.get());
874 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200875 flag1 = false;
876 // Execute all pending calls. The id == 5 call should not execute again.
877 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800878 EXPECT_FALSE(flag1.get());
879 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200880}
Mirko Bonadeie10b1632018-12-11 18:43:40 +0100881
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100882void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
883 *result = thread->IsCurrent();
884 event->Set();
885}
886
887void WaitAndSetEvent(Event* wait_event, Event* set_event) {
888 wait_event->Wait(Event::kForever);
889 set_event->Set();
890}
891
892// A functor that keeps track of the number of copies and moves.
893class LifeCycleFunctor {
894 public:
895 struct Stats {
896 size_t copy_count = 0;
897 size_t move_count = 0;
898 };
899
900 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
901 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
902 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
903
904 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
905 stats_ = other.stats_;
906 event_ = other.event_;
907 ++stats_->copy_count;
908 return *this;
909 }
910
911 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
912 stats_ = other.stats_;
913 event_ = other.event_;
914 ++stats_->move_count;
915 return *this;
916 }
917
918 void operator()() { event_->Set(); }
919
920 private:
921 Stats* stats_;
922 Event* event_;
923};
924
925// A functor that verifies the thread it was destroyed on.
926class DestructionFunctor {
927 public:
928 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
929 : thread_(thread),
930 thread_was_current_(thread_was_current),
931 event_(event) {}
932 ~DestructionFunctor() {
933 // Only signal the event if this was the functor that was invoked to avoid
934 // the event being signaled due to the destruction of temporary/moved
935 // versions of this object.
936 if (was_invoked_) {
937 *thread_was_current_ = thread_->IsCurrent();
938 event_->Set();
939 }
940 }
941
942 void operator()() { was_invoked_ = true; }
943
944 private:
945 Thread* thread_;
946 bool* thread_was_current_;
947 Event* event_;
948 bool was_invoked_ = false;
949};
950
951TEST(ThreadPostTaskTest, InvokesWithBind) {
952 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
953 background_thread->Start();
954
955 Event event;
956 background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
957 event.Wait(Event::kForever);
958}
959
960TEST(ThreadPostTaskTest, InvokesWithLambda) {
961 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
962 background_thread->Start();
963
964 Event event;
965 background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
966 event.Wait(Event::kForever);
967}
968
969TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
970 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
971 background_thread->Start();
972
973 LifeCycleFunctor::Stats stats;
974 Event event;
975 LifeCycleFunctor functor(&stats, &event);
976 background_thread->PostTask(RTC_FROM_HERE, functor);
977 event.Wait(Event::kForever);
978
979 EXPECT_EQ(1u, stats.copy_count);
980 EXPECT_EQ(0u, stats.move_count);
981}
982
983TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
984 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
985 background_thread->Start();
986
987 LifeCycleFunctor::Stats stats;
988 Event event;
989 LifeCycleFunctor functor(&stats, &event);
990 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
991 event.Wait(Event::kForever);
992
993 EXPECT_EQ(0u, stats.copy_count);
994 EXPECT_EQ(1u, stats.move_count);
995}
996
997TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
998 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
999 background_thread->Start();
1000
1001 LifeCycleFunctor::Stats stats;
1002 Event event;
1003 LifeCycleFunctor functor(&stats, &event);
1004 LifeCycleFunctor& functor_ref = functor;
1005 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1006 event.Wait(Event::kForever);
1007
1008 EXPECT_EQ(1u, stats.copy_count);
1009 EXPECT_EQ(0u, stats.move_count);
1010}
1011
1012TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
1013 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1014 background_thread->Start();
1015
1016 Event event;
1017 bool was_invoked_on_background_thread = false;
1018 DestructionFunctor functor(background_thread.get(),
1019 &was_invoked_on_background_thread, &event);
1020 background_thread->PostTask(RTC_FROM_HERE, functor);
1021 event.Wait(Event::kForever);
1022
1023 EXPECT_TRUE(was_invoked_on_background_thread);
1024}
1025
1026TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
1027 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1028 background_thread->Start();
1029
1030 Event event;
1031 bool was_invoked_on_background_thread = false;
1032 DestructionFunctor functor(background_thread.get(),
1033 &was_invoked_on_background_thread, &event);
1034 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
1035 event.Wait(Event::kForever);
1036
1037 EXPECT_TRUE(was_invoked_on_background_thread);
1038}
1039
1040TEST(ThreadPostTaskTest,
1041 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1042 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1043 background_thread->Start();
1044
1045 Event event;
1046 bool was_invoked_on_background_thread = false;
1047 DestructionFunctor functor(background_thread.get(),
1048 &was_invoked_on_background_thread, &event);
1049 DestructionFunctor& functor_ref = functor;
1050 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1051 event.Wait(Event::kForever);
1052
1053 EXPECT_TRUE(was_invoked_on_background_thread);
1054}
1055
1056TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1057 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1058 background_thread->Start();
1059
1060 Event event;
1061 bool was_invoked_on_background_thread = false;
1062 background_thread->PostTask(RTC_FROM_HERE,
1063 Bind(&ThreadIsCurrent, background_thread.get(),
1064 &was_invoked_on_background_thread, &event));
1065 event.Wait(Event::kForever);
1066
1067 EXPECT_TRUE(was_invoked_on_background_thread);
1068}
1069
1070TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1071 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1072 background_thread->Start();
1073
1074 // The first event ensures that SendSingleMessage() is not blocking this
1075 // thread. The second event ensures that the message is processed.
1076 Event event_set_by_test_thread;
1077 Event event_set_by_background_thread;
1078 background_thread->PostTask(RTC_FROM_HERE,
1079 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1080 &event_set_by_background_thread));
1081 event_set_by_test_thread.Set();
1082 event_set_by_background_thread.Wait(Event::kForever);
1083}
1084
1085TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1086 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1087 background_thread->Start();
1088
1089 Event first;
1090 Event second;
1091 Event third;
1092 Event fourth;
1093
1094 background_thread->PostTask(RTC_FROM_HERE,
1095 Bind(&WaitAndSetEvent, &first, &second));
1096 background_thread->PostTask(RTC_FROM_HERE,
1097 Bind(&WaitAndSetEvent, &second, &third));
1098 background_thread->PostTask(RTC_FROM_HERE,
1099 Bind(&WaitAndSetEvent, &third, &fourth));
1100
1101 // All tasks have been posted before the first one is unblocked.
1102 first.Set();
1103 // Only if the chain is invoked in posted order will the last event be set.
1104 fourth.Wait(Event::kForever);
1105}
1106
Steve Antonbcc1a762019-12-11 11:21:53 -08001107TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1108 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1109 background_thread->Start();
1110
1111 // The first event ensures that SendSingleMessage() is not blocking this
1112 // thread. The second event ensures that the message is processed.
1113 Event event_set_by_test_thread;
1114 Event event_set_by_background_thread;
1115 background_thread->PostDelayedTask(
1116 RTC_FROM_HERE,
1117 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1118 &event_set_by_background_thread),
1119 /*milliseconds=*/10);
1120 event_set_by_test_thread.Set();
1121 event_set_by_background_thread.Wait(Event::kForever);
1122}
1123
1124TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001125 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001126 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1127 background_thread->Start();
1128
1129 Event first;
1130 Event second;
1131 Event third;
1132 Event fourth;
1133
1134 background_thread->PostDelayedTask(RTC_FROM_HERE,
1135 Bind(&WaitAndSetEvent, &third, &fourth),
1136 /*milliseconds=*/11);
1137 background_thread->PostDelayedTask(RTC_FROM_HERE,
1138 Bind(&WaitAndSetEvent, &first, &second),
1139 /*milliseconds=*/9);
1140 background_thread->PostDelayedTask(RTC_FROM_HERE,
1141 Bind(&WaitAndSetEvent, &second, &third),
1142 /*milliseconds=*/10);
1143
1144 // All tasks have been posted before the first one is unblocked.
1145 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001146 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001147 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001148 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001149}
1150
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001151class ThreadFactory : public webrtc::TaskQueueFactory {
1152 public:
1153 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1154 CreateTaskQueue(absl::string_view /* name */,
1155 Priority /*priority*/) const override {
1156 std::unique_ptr<Thread> thread = Thread::Create();
1157 thread->Start();
1158 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1159 thread.release());
1160 }
1161};
1162
1163using ::webrtc::TaskQueueTest;
1164
1165INSTANTIATE_TEST_SUITE_P(RtcThread,
1166 TaskQueueTest,
1167 ::testing::Values(std::make_unique<ThreadFactory>));
1168
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001169} // namespace
1170} // namespace rtc