blob: fb54bb557d1dfeaddd47b7215b63f1875fad19f5 [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"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027
28#if defined(WEBRTC_WIN)
29#include <comdef.h> // NOLINT
30#endif
31
Mirko Bonadeie10b1632018-12-11 18:43:40 +010032namespace rtc {
33namespace {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034
Sebastian Jansson73387822020-01-16 11:15:35 +010035using ::webrtc::ToQueuedTask;
36
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037// Generates a sequence of numbers (collaboratively).
38class TestGenerator {
39 public:
40 TestGenerator() : last(0), count(0) {}
41
42 int Next(int prev) {
43 int result = prev + last;
44 last = result;
45 count += 1;
46 return result;
47 }
48
49 int last;
50 int count;
51};
52
53struct TestMessage : public MessageData {
54 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055
56 int value;
57};
58
59// Receives on a socket and sends by posting messages.
60class SocketClient : public TestGenerator, public sigslot::has_slots<> {
61 public:
Yves Gerey665174f2018-06-19 15:03:05 +020062 SocketClient(AsyncSocket* socket,
63 const SocketAddress& addr,
64 Thread* post_thread,
65 MessageHandler* phandler)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066 : socket_(AsyncUDPSocket::Create(socket, addr)),
67 post_thread_(post_thread),
68 post_handler_(phandler) {
69 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
70 }
71
Steve Anton9de3aac2017-10-24 10:08:26 -070072 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000073
74 SocketAddress address() const { return socket_->GetLocalAddress(); }
75
Yves Gerey665174f2018-06-19 15:03:05 +020076 void OnPacket(AsyncPacketSocket* socket,
77 const char* buf,
78 size_t size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079 const SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +010080 const int64_t& packet_time_us) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020081 EXPECT_EQ(size, sizeof(uint32_t));
82 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
83 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070085 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
86 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 }
88
89 private:
90 AsyncUDPSocket* socket_;
91 Thread* post_thread_;
92 MessageHandler* post_handler_;
93};
94
95// Receives messages and sends on a socket.
96class MessageClient : public MessageHandler, public TestGenerator {
97 public:
Yves Gerey665174f2018-06-19 15:03:05 +020098 MessageClient(Thread* pth, Socket* socket) : socket_(socket) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099
Steve Anton9de3aac2017-10-24 10:08:26 -0700100 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000101
Steve Anton9de3aac2017-10-24 10:08:26 -0700102 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
104 int result = Next(msg->value);
105 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
106 delete msg;
107 }
108
109 private:
110 Socket* socket_;
111};
112
deadbeefaea92932017-05-23 12:55:03 -0700113class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114 public:
tommie7251592017-07-14 14:44:46 -0700115 CustomThread()
116 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700117 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000119
Yves Gerey665174f2018-06-19 15:03:05 +0200120 bool WrapCurrent() { return Thread::WrapCurrent(); }
121 void UnwrapCurrent() { Thread::UnwrapCurrent(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000122};
123
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124// A thread that does nothing when it runs and signals an event
125// when it is destroyed.
126class SignalWhenDestroyedThread : public Thread {
127 public:
128 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700129 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
130 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131
Steve Anton9de3aac2017-10-24 10:08:26 -0700132 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 Stop();
134 event_->Set();
135 }
136
Steve Anton9de3aac2017-10-24 10:08:26 -0700137 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 // Do nothing.
139 }
140
141 private:
142 Event* event_;
143};
144
nissed9b75be2015-11-16 00:54:07 -0800145// A bool wrapped in a mutex, to avoid data races. Using a volatile
146// bool should be sufficient for correct code ("eventual consistency"
147// between caches is sufficient), but we can't tell the compiler about
148// that, and then tsan complains about a data race.
149
150// See also discussion at
151// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
152
153// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
154// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700155// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800156// performance critical, use a plain critical section for the time
157// being.
158
159class AtomicBool {
160 public:
161 explicit AtomicBool(bool value = false) : flag_(value) {}
162 AtomicBool& operator=(bool value) {
163 CritScope scoped_lock(&cs_);
164 flag_ = value;
165 return *this;
166 }
167 bool get() const {
168 CritScope scoped_lock(&cs_);
169 return flag_;
170 }
171
172 private:
pbos5ad935c2016-01-25 03:52:44 -0800173 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800174 bool flag_;
175};
176
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177// Function objects to test Thread::Invoke.
178struct FunctorA {
179 int operator()() { return 42; }
180};
181class FunctorB {
182 public:
nissed9b75be2015-11-16 00:54:07 -0800183 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
Yves Gerey665174f2018-06-19 15:03:05 +0200184 void operator()() {
185 if (flag_)
186 *flag_ = true;
187 }
188
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000189 private:
nissed9b75be2015-11-16 00:54:07 -0800190 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191};
192struct FunctorC {
193 int operator()() {
194 Thread::Current()->ProcessMessages(50);
195 return 24;
196 }
197};
Cameron Pickettd132ce12018-03-12 16:07:37 -0700198struct FunctorD {
199 public:
200 explicit FunctorD(AtomicBool* flag) : flag_(flag) {}
201 FunctorD(FunctorD&&) = default;
202 FunctorD& operator=(FunctorD&&) = default;
Yves Gerey665174f2018-06-19 15:03:05 +0200203 void operator()() {
204 if (flag_)
205 *flag_ = true;
206 }
207
Cameron Pickettd132ce12018-03-12 16:07:37 -0700208 private:
209 AtomicBool* flag_;
210 RTC_DISALLOW_COPY_AND_ASSIGN(FunctorD);
211};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212
213// See: https://code.google.com/p/webrtc/issues/detail?id=2409
214TEST(ThreadTest, DISABLED_Main) {
215 const SocketAddress addr("127.0.0.1", 0);
216
217 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700218 auto th1 = Thread::CreateWithSocketServer();
219 Socket* socket =
220 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
221 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222
223 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700224 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000225 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700226 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
227 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228
229 socket->Connect(sock_client.address());
230
tommie7251592017-07-14 14:44:46 -0700231 th1->Start();
232 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000233
234 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700235 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236
237 // Give the clients a little while to run.
238 // Messages will be processed at 100, 300, 500, 700, 900.
239 Thread* th_main = Thread::Current();
240 th_main->ProcessMessages(1000);
241
242 // Stop the sending client. Give the receiver a bit longer to run, in case
243 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700244 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700246 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247
248 // Make sure the results were correct
249 EXPECT_EQ(5, msg_client.count);
250 EXPECT_EQ(34, msg_client.last);
251 EXPECT_EQ(5, sock_client.count);
252 EXPECT_EQ(55, sock_client.last);
253}
254
255// Test that setting thread names doesn't cause a malfunction.
256// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000257TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 // Default name
tommie7251592017-07-14 14:44:46 -0700259 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 EXPECT_TRUE(thread->Start());
261 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700263 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800264 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 EXPECT_TRUE(thread->Start());
266 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 // Really long name
tommie7251592017-07-14 14:44:46 -0700268 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
270 EXPECT_TRUE(thread->Start());
271 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272}
273
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000274TEST(ThreadTest, Wrap) {
275 Thread* current_thread = Thread::Current();
Niels Möller5a8f8602019-06-12 11:30:59 +0200276 ThreadManager::Instance()->SetCurrentThread(nullptr);
277
278 {
279 CustomThread cthread;
280 EXPECT_TRUE(cthread.WrapCurrent());
281 EXPECT_EQ(&cthread, Thread::Current());
282 EXPECT_TRUE(cthread.RunningForTest());
283 EXPECT_FALSE(cthread.IsOwned());
284 cthread.UnwrapCurrent();
285 EXPECT_FALSE(cthread.RunningForTest());
286 }
287 ThreadManager::Instance()->SetCurrentThread(current_thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000288}
289
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000290TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700292 auto thread = Thread::CreateWithSocketServer();
293 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700295 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800296 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700298 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800299 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000300 // Try calling bare functions.
301 struct LocalFuncs {
302 static int Func1() { return 999; }
303 static void Func2() {}
304 };
tommie7251592017-07-14 14:44:46 -0700305 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
306 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307}
308
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000309// Verifies that two threads calling Invoke on each other at the same time does
310// not deadlock.
311TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
312 AutoThread thread;
313 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800314 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000315
tommie7251592017-07-14 14:44:46 -0700316 auto other_thread = Thread::CreateWithSocketServer();
317 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000318
319 struct LocalFuncs {
320 static void Set(bool* out) { *out = true; }
321 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700322 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000323 }
324 };
325
326 bool called = false;
tommie7251592017-07-14 14:44:46 -0700327 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700328 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000329
330 EXPECT_TRUE(called);
331}
332
333// Verifies that if thread A invokes a call on thread B and thread C is trying
334// to invoke A at the same time, thread A does not handle C's invoke while
335// invoking B.
336TEST(ThreadTest, ThreeThreadsInvoke) {
337 AutoThread thread;
338 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700339 auto thread_b = Thread::CreateWithSocketServer();
340 auto thread_c = Thread::CreateWithSocketServer();
341 thread_b->Start();
342 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000343
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000344 class LockedBool {
345 public:
346 explicit LockedBool(bool value) : value_(value) {}
347
348 void Set(bool value) {
349 CritScope lock(&crit_);
350 value_ = value;
351 }
352
353 bool Get() {
354 CritScope lock(&crit_);
355 return value_;
356 }
357
358 private:
359 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700360 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000361 };
362
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000363 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000364 static void Set(LockedBool* out) { out->Set(true); }
365 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700366 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000367 }
368
369 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000370 static void SetAndInvokeSet(LockedBool* out,
371 Thread* thread,
372 LockedBool* out_inner) {
373 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000374 InvokeSet(thread, out_inner);
375 }
376
377 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
378 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800379 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
380 Thread* thread1,
381 Thread* thread2,
382 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000383 CriticalSection crit;
384 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000385
deadbeef162cb532017-02-23 17:10:07 -0800386 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700387 RTC_FROM_HERE, thread1,
388 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000389
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000390 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000391 }
392 };
393
deadbeef162cb532017-02-23 17:10:07 -0800394 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000395 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000396
397 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
398 // Thread B returns when C receives the call and C should be blocked until A
399 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700400 thread_b->Invoke<void>(RTC_FROM_HERE,
401 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
402 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000403 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000404
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000405 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000406}
407
jbauch25d1f282016-02-05 00:25:02 -0800408// Set the name on a thread when the underlying QueueDestroyed signal is
409// triggered. This causes an error if the object is already partially
410// destroyed.
411class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
412 public:
413 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
414 thread->SignalQueueDestroyed.connect(
415 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
416 }
417
418 void OnQueueDestroyed() {
419 // Makes sure that if we access the Thread while it's being destroyed, that
420 // it doesn't cause a problem because the vtable has been modified.
421 thread_->SetName("foo", nullptr);
422 }
423
424 private:
425 Thread* thread_;
426};
427
428TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700429 auto thread1 = Thread::CreateWithSocketServer();
430 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
431 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800432
433 Thread* thread2 = new AutoThread();
434 SetNameOnSignalQueueDestroyedTester tester2(thread2);
435 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800436}
437
Sebastian Jansson73387822020-01-16 11:15:35 +0100438class ThreadQueueTest : public ::testing::Test, public Thread {
439 public:
440 ThreadQueueTest() : Thread(SocketServer::CreateDefault(), true) {}
441 bool IsLocked_Worker() {
442 if (!CritForTest()->TryEnter()) {
443 return true;
444 }
445 CritForTest()->Leave();
446 return false;
447 }
448 bool IsLocked() {
449 // We have to do this on a worker thread, or else the TryEnter will
450 // succeed, since our critical sections are reentrant.
451 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
452 worker->Start();
453 return worker->Invoke<bool>(
454 RTC_FROM_HERE, rtc::Bind(&ThreadQueueTest::IsLocked_Worker, this));
455 }
456};
457
458struct DeletedLockChecker {
459 DeletedLockChecker(ThreadQueueTest* test, bool* was_locked, bool* deleted)
460 : test(test), was_locked(was_locked), deleted(deleted) {}
461 ~DeletedLockChecker() {
462 *deleted = true;
463 *was_locked = test->IsLocked();
464 }
465 ThreadQueueTest* test;
466 bool* was_locked;
467 bool* deleted;
468};
469
470static void DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(Thread* q) {
471 EXPECT_TRUE(q != nullptr);
472 int64_t now = TimeMillis();
473 q->PostAt(RTC_FROM_HERE, now, nullptr, 3);
474 q->PostAt(RTC_FROM_HERE, now - 2, nullptr, 0);
475 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 1);
476 q->PostAt(RTC_FROM_HERE, now, nullptr, 4);
477 q->PostAt(RTC_FROM_HERE, now - 1, nullptr, 2);
478
479 Message msg;
480 for (size_t i = 0; i < 5; ++i) {
481 memset(&msg, 0, sizeof(msg));
482 EXPECT_TRUE(q->Get(&msg, 0));
483 EXPECT_EQ(i, msg.message_id);
484 }
485
486 EXPECT_FALSE(q->Get(&msg, 0)); // No more messages
487}
488
489TEST_F(ThreadQueueTest, DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder) {
490 Thread q(SocketServer::CreateDefault(), true);
491 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q);
492
493 NullSocketServer nullss;
494 Thread q_nullss(&nullss, true);
495 DelayedPostsWithIdenticalTimesAreProcessedInFifoOrder(&q_nullss);
496}
497
498TEST_F(ThreadQueueTest, DisposeNotLocked) {
499 bool was_locked = true;
500 bool deleted = false;
501 DeletedLockChecker* d = new DeletedLockChecker(this, &was_locked, &deleted);
502 Dispose(d);
503 Message msg;
504 EXPECT_FALSE(Get(&msg, 0));
505 EXPECT_TRUE(deleted);
506 EXPECT_FALSE(was_locked);
507}
508
509class DeletedMessageHandler : public MessageHandler {
510 public:
511 explicit DeletedMessageHandler(bool* deleted) : deleted_(deleted) {}
512 ~DeletedMessageHandler() override { *deleted_ = true; }
513 void OnMessage(Message* msg) override {}
514
515 private:
516 bool* deleted_;
517};
518
519TEST_F(ThreadQueueTest, DiposeHandlerWithPostedMessagePending) {
520 bool deleted = false;
521 DeletedMessageHandler* handler = new DeletedMessageHandler(&deleted);
522 // First, post a dispose.
523 Dispose(handler);
524 // Now, post a message, which should *not* be returned by Get().
525 Post(RTC_FROM_HERE, handler, 1);
526 Message msg;
527 EXPECT_FALSE(Get(&msg, 0));
528 EXPECT_TRUE(deleted);
529}
530
531// Ensure that ProcessAllMessageQueues does its essential function; process
532// all messages (both delayed and non delayed) up until the current time, on
533// all registered message queues.
534TEST(ThreadManager, ProcessAllMessageQueues) {
535 Event entered_process_all_message_queues(true, false);
536 auto a = Thread::CreateWithSocketServer();
537 auto b = Thread::CreateWithSocketServer();
538 a->Start();
539 b->Start();
540
541 volatile int messages_processed = 0;
542 auto incrementer = [&messages_processed,
543 &entered_process_all_message_queues] {
544 // Wait for event as a means to ensure Increment doesn't occur outside
545 // of ProcessAllMessageQueues. The event is set by a message posted to
546 // the main thread, which is guaranteed to be handled inside
547 // ProcessAllMessageQueues.
548 entered_process_all_message_queues.Wait(Event::kForever);
549 AtomicOps::Increment(&messages_processed);
550 };
551 auto event_signaler = [&entered_process_all_message_queues] {
552 entered_process_all_message_queues.Set();
553 };
554
555 // Post messages (both delayed and non delayed) to both threads.
556 a->PostTask(ToQueuedTask(incrementer));
557 b->PostTask(ToQueuedTask(incrementer));
558 a->PostDelayedTask(ToQueuedTask(incrementer), 0);
559 b->PostDelayedTask(ToQueuedTask(incrementer), 0);
560 rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
561
562 ThreadManager::ProcessAllMessageQueuesForTesting();
563 EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
564}
565
566// Test that ProcessAllMessageQueues doesn't hang if a thread is quitting.
567TEST(ThreadManager, ProcessAllMessageQueuesWithQuittingThread) {
568 auto t = Thread::CreateWithSocketServer();
569 t->Start();
570 t->Quit();
571 ThreadManager::ProcessAllMessageQueuesForTesting();
572}
573
574// Test that ProcessAllMessageQueues doesn't hang if a queue clears its
575// messages.
576TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
577 Event entered_process_all_message_queues(true, false);
578 auto t = Thread::CreateWithSocketServer();
579 t->Start();
580
581 auto clearer = [&entered_process_all_message_queues] {
582 // Wait for event as a means to ensure Clear doesn't occur outside of
583 // ProcessAllMessageQueues. The event is set by a message posted to the
584 // main thread, which is guaranteed to be handled inside
585 // ProcessAllMessageQueues.
586 entered_process_all_message_queues.Wait(Event::kForever);
587 rtc::Thread::Current()->Clear(nullptr);
588 };
589 auto event_signaler = [&entered_process_all_message_queues] {
590 entered_process_all_message_queues.Set();
591 };
592
593 // Post messages (both delayed and non delayed) to both threads.
594 t->PostTask(RTC_FROM_HERE, clearer);
595 rtc::Thread::Current()->PostTask(RTC_FROM_HERE, event_signaler);
596 ThreadManager::ProcessAllMessageQueuesForTesting();
597}
598
599class RefCountedHandler : public MessageHandler, public rtc::RefCountInterface {
600 public:
601 void OnMessage(Message* msg) override {}
602};
603
604class EmptyHandler : public MessageHandler {
605 public:
606 void OnMessage(Message* msg) override {}
607};
608
609TEST(ThreadManager, ClearReentrant) {
610 std::unique_ptr<Thread> t(Thread::Create());
611 EmptyHandler handler;
612 RefCountedHandler* inner_handler(
613 new rtc::RefCountedObject<RefCountedHandler>());
614 // When the empty handler is destroyed, it will clear messages queued for
615 // itself. The message to be cleared itself wraps a MessageHandler object
616 // (RefCountedHandler) so this will cause the message queue to be cleared
617 // again in a re-entrant fashion, which previously triggered a DCHECK.
618 // The inner handler will be removed in a re-entrant fashion from the
619 // message queue of the thread while the outer handler is removed, verifying
620 // that the iterator is not invalidated in "MessageQueue::Clear".
621 t->Post(RTC_FROM_HERE, inner_handler, 0);
622 t->Post(RTC_FROM_HERE, &handler, 0,
623 new ScopedRefMessageData<RefCountedHandler>(inner_handler));
624}
625
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200626class AsyncInvokeTest : public ::testing::Test {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000627 public:
628 void IntCallback(int value) {
629 EXPECT_EQ(expected_thread_, Thread::Current());
630 int_value_ = value;
631 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000632 void SetExpectedThreadForIntCallback(Thread* thread) {
633 expected_thread_ = thread;
634 }
635
636 protected:
637 enum { kWaitTimeout = 1000 };
Yves Gerey665174f2018-06-19 15:03:05 +0200638 AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000639
640 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000641 Thread* expected_thread_;
642};
643
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000644TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000645 AsyncInvoker invoker;
646 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700647 auto thread = Thread::CreateWithSocketServer();
648 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000649 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800650 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700651 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800652 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700653 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000654}
655
Cameron Pickettd132ce12018-03-12 16:07:37 -0700656TEST_F(AsyncInvokeTest, NonCopyableFunctor) {
657 AsyncInvoker invoker;
658 // Create and start the thread.
659 auto thread = Thread::CreateWithSocketServer();
660 thread->Start();
661 // Try calling functor.
662 AtomicBool called;
663 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorD(&called));
664 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
665 thread->Stop();
666}
667
deadbeef162cb532017-02-23 17:10:07 -0800668TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
669 // Use these events to get in a state where the functor is in the middle of
670 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
671 // is run.
Niels Möllerc572ff32018-11-07 08:43:50 +0100672 Event functor_started;
673 Event functor_continue;
674 Event functor_finished;
deadbeef162cb532017-02-23 17:10:07 -0800675
tommie7251592017-07-14 14:44:46 -0700676 auto thread = Thread::CreateWithSocketServer();
677 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800678 volatile bool invoker_destroyed = false;
679 {
deadbeef3af63b02017-08-08 17:59:47 -0700680 auto functor = [&functor_started, &functor_continue, &functor_finished,
681 &invoker_destroyed] {
682 functor_started.Set();
683 functor_continue.Wait(Event::kForever);
684 rtc::Thread::Current()->SleepMs(kWaitTimeout);
685 EXPECT_FALSE(invoker_destroyed);
686 functor_finished.Set();
687 };
deadbeef162cb532017-02-23 17:10:07 -0800688 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700689 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800690 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700691
deadbeef3af63b02017-08-08 17:59:47 -0700692 // Destroy the invoker while the functor is still executing (doing
693 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700694 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800695 }
696
697 // If the destructor DIDN'T wait for the functor to finish executing, it will
698 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
699 // second.
700 invoker_destroyed = true;
701 functor_finished.Wait(Event::kForever);
702}
703
deadbeef3af63b02017-08-08 17:59:47 -0700704// Variant of the above test where the async-invoked task calls AsyncInvoke
705// *again*, for the thread on which the AsyncInvoker is currently being
706// destroyed. This shouldn't deadlock or crash; this second invocation should
707// just be ignored.
708TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
Niels Möllerc572ff32018-11-07 08:43:50 +0100709 Event functor_started;
deadbeef3af63b02017-08-08 17:59:47 -0700710 // Flag used to verify that the recursively invoked task never actually runs.
711 bool reentrant_functor_run = false;
712
713 Thread* main = Thread::Current();
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200714 Thread thread(std::make_unique<NullSocketServer>());
deadbeef3af63b02017-08-08 17:59:47 -0700715 thread.Start();
716 {
717 AsyncInvoker invoker;
718 auto reentrant_functor = [&reentrant_functor_run] {
719 reentrant_functor_run = true;
720 };
721 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
722 functor_started.Set();
723 Thread::Current()->SleepMs(kWaitTimeout);
724 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
725 };
726 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
727 // task on |main|. But this second queued task should never run, since the
728 // destructor will be entered before it's even invoked.
729 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
730 functor_started.Wait(Event::kForever);
731 }
732 EXPECT_FALSE(reentrant_functor_run);
733}
734
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000735TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000736 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800737 AtomicBool flag1;
738 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000739 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700740 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
741 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000742 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800743 EXPECT_FALSE(flag1.get());
744 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000745 // Force them to run now.
746 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800747 EXPECT_TRUE(flag1.get());
748 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749}
750
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000751TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000752 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800753 AtomicBool flag1;
754 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000755 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700756 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700758 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000759 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800760 EXPECT_FALSE(flag1.get());
761 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000762 // Execute pending calls with id == 5.
763 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800764 EXPECT_TRUE(flag1.get());
765 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000766 flag1 = false;
767 // Execute all pending calls. The id == 5 call should not execute again.
768 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800769 EXPECT_FALSE(flag1.get());
770 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000771}
772
Mirko Bonadei6a489f22019-04-09 15:11:12 +0200773class GuardedAsyncInvokeTest : public ::testing::Test {
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200774 public:
775 void IntCallback(int value) {
776 EXPECT_EQ(expected_thread_, Thread::Current());
777 int_value_ = value;
778 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200779 void SetExpectedThreadForIntCallback(Thread* thread) {
780 expected_thread_ = thread;
781 }
782
783 protected:
784 const static int kWaitTimeout = 1000;
Yves Gerey665174f2018-06-19 15:03:05 +0200785 GuardedAsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200786
787 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200788 Thread* expected_thread_;
789};
790
791// Functor for creating an invoker.
792struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700793 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
794 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200795 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700796 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200797};
798
799// Test that we can call AsyncInvoke<void>() after the thread died.
800TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
801 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700802 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200803 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700804 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200805 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700806 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200807 // Kill |thread|.
808 thread = nullptr;
809 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800810 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700811 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200812 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800813 WAIT(called.get(), kWaitTimeout);
814 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200815}
816
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200817// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
818// when Thread is still alive.
819TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
820 GuardedAsyncInvoker invoker;
821 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800822 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700823 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800824 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200825}
826
Cameron Pickettd132ce12018-03-12 16:07:37 -0700827TEST_F(GuardedAsyncInvokeTest, NonCopyableFunctor) {
828 GuardedAsyncInvoker invoker;
829 // Try calling functor.
830 AtomicBool called;
831 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorD(&called)));
832 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
833}
834
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200835TEST_F(GuardedAsyncInvokeTest, Flush) {
836 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800837 AtomicBool flag1;
838 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200839 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700840 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
841 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200842 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800843 EXPECT_FALSE(flag1.get());
844 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200845 // Force them to run now.
846 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800847 EXPECT_TRUE(flag1.get());
848 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200849}
850
851TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
852 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800853 AtomicBool flag1;
854 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200855 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700856 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
857 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200858 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800859 EXPECT_FALSE(flag1.get());
860 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200861 // Execute pending calls with id == 5.
862 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800863 EXPECT_TRUE(flag1.get());
864 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200865 flag1 = false;
866 // Execute all pending calls. The id == 5 call should not execute again.
867 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800868 EXPECT_FALSE(flag1.get());
869 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200870}
Mirko Bonadeie10b1632018-12-11 18:43:40 +0100871
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100872void ThreadIsCurrent(Thread* thread, bool* result, Event* event) {
873 *result = thread->IsCurrent();
874 event->Set();
875}
876
877void WaitAndSetEvent(Event* wait_event, Event* set_event) {
878 wait_event->Wait(Event::kForever);
879 set_event->Set();
880}
881
882// A functor that keeps track of the number of copies and moves.
883class LifeCycleFunctor {
884 public:
885 struct Stats {
886 size_t copy_count = 0;
887 size_t move_count = 0;
888 };
889
890 LifeCycleFunctor(Stats* stats, Event* event) : stats_(stats), event_(event) {}
891 LifeCycleFunctor(const LifeCycleFunctor& other) { *this = other; }
892 LifeCycleFunctor(LifeCycleFunctor&& other) { *this = std::move(other); }
893
894 LifeCycleFunctor& operator=(const LifeCycleFunctor& other) {
895 stats_ = other.stats_;
896 event_ = other.event_;
897 ++stats_->copy_count;
898 return *this;
899 }
900
901 LifeCycleFunctor& operator=(LifeCycleFunctor&& other) {
902 stats_ = other.stats_;
903 event_ = other.event_;
904 ++stats_->move_count;
905 return *this;
906 }
907
908 void operator()() { event_->Set(); }
909
910 private:
911 Stats* stats_;
912 Event* event_;
913};
914
915// A functor that verifies the thread it was destroyed on.
916class DestructionFunctor {
917 public:
918 DestructionFunctor(Thread* thread, bool* thread_was_current, Event* event)
919 : thread_(thread),
920 thread_was_current_(thread_was_current),
921 event_(event) {}
922 ~DestructionFunctor() {
923 // Only signal the event if this was the functor that was invoked to avoid
924 // the event being signaled due to the destruction of temporary/moved
925 // versions of this object.
926 if (was_invoked_) {
927 *thread_was_current_ = thread_->IsCurrent();
928 event_->Set();
929 }
930 }
931
932 void operator()() { was_invoked_ = true; }
933
934 private:
935 Thread* thread_;
936 bool* thread_was_current_;
937 Event* event_;
938 bool was_invoked_ = false;
939};
940
941TEST(ThreadPostTaskTest, InvokesWithBind) {
942 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
943 background_thread->Start();
944
945 Event event;
946 background_thread->PostTask(RTC_FROM_HERE, Bind(&Event::Set, &event));
947 event.Wait(Event::kForever);
948}
949
950TEST(ThreadPostTaskTest, InvokesWithLambda) {
951 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
952 background_thread->Start();
953
954 Event event;
955 background_thread->PostTask(RTC_FROM_HERE, [&event] { event.Set(); });
956 event.Wait(Event::kForever);
957}
958
959TEST(ThreadPostTaskTest, InvokesWithCopiedFunctor) {
960 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
961 background_thread->Start();
962
963 LifeCycleFunctor::Stats stats;
964 Event event;
965 LifeCycleFunctor functor(&stats, &event);
966 background_thread->PostTask(RTC_FROM_HERE, functor);
967 event.Wait(Event::kForever);
968
969 EXPECT_EQ(1u, stats.copy_count);
970 EXPECT_EQ(0u, stats.move_count);
971}
972
973TEST(ThreadPostTaskTest, InvokesWithMovedFunctor) {
974 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
975 background_thread->Start();
976
977 LifeCycleFunctor::Stats stats;
978 Event event;
979 LifeCycleFunctor functor(&stats, &event);
980 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
981 event.Wait(Event::kForever);
982
983 EXPECT_EQ(0u, stats.copy_count);
984 EXPECT_EQ(1u, stats.move_count);
985}
986
987TEST(ThreadPostTaskTest, InvokesWithReferencedFunctorShouldCopy) {
988 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
989 background_thread->Start();
990
991 LifeCycleFunctor::Stats stats;
992 Event event;
993 LifeCycleFunctor functor(&stats, &event);
994 LifeCycleFunctor& functor_ref = functor;
995 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
996 event.Wait(Event::kForever);
997
998 EXPECT_EQ(1u, stats.copy_count);
999 EXPECT_EQ(0u, stats.move_count);
1000}
1001
1002TEST(ThreadPostTaskTest, InvokesWithCopiedFunctorDestroyedOnTargetThread) {
1003 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1004 background_thread->Start();
1005
1006 Event event;
1007 bool was_invoked_on_background_thread = false;
1008 DestructionFunctor functor(background_thread.get(),
1009 &was_invoked_on_background_thread, &event);
1010 background_thread->PostTask(RTC_FROM_HERE, functor);
1011 event.Wait(Event::kForever);
1012
1013 EXPECT_TRUE(was_invoked_on_background_thread);
1014}
1015
1016TEST(ThreadPostTaskTest, InvokesWithMovedFunctorDestroyedOnTargetThread) {
1017 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1018 background_thread->Start();
1019
1020 Event event;
1021 bool was_invoked_on_background_thread = false;
1022 DestructionFunctor functor(background_thread.get(),
1023 &was_invoked_on_background_thread, &event);
1024 background_thread->PostTask(RTC_FROM_HERE, std::move(functor));
1025 event.Wait(Event::kForever);
1026
1027 EXPECT_TRUE(was_invoked_on_background_thread);
1028}
1029
1030TEST(ThreadPostTaskTest,
1031 InvokesWithReferencedFunctorShouldCopyAndDestroyedOnTargetThread) {
1032 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1033 background_thread->Start();
1034
1035 Event event;
1036 bool was_invoked_on_background_thread = false;
1037 DestructionFunctor functor(background_thread.get(),
1038 &was_invoked_on_background_thread, &event);
1039 DestructionFunctor& functor_ref = functor;
1040 background_thread->PostTask(RTC_FROM_HERE, functor_ref);
1041 event.Wait(Event::kForever);
1042
1043 EXPECT_TRUE(was_invoked_on_background_thread);
1044}
1045
1046TEST(ThreadPostTaskTest, InvokesOnBackgroundThread) {
1047 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1048 background_thread->Start();
1049
1050 Event event;
1051 bool was_invoked_on_background_thread = false;
1052 background_thread->PostTask(RTC_FROM_HERE,
1053 Bind(&ThreadIsCurrent, background_thread.get(),
1054 &was_invoked_on_background_thread, &event));
1055 event.Wait(Event::kForever);
1056
1057 EXPECT_TRUE(was_invoked_on_background_thread);
1058}
1059
1060TEST(ThreadPostTaskTest, InvokesAsynchronously) {
1061 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1062 background_thread->Start();
1063
1064 // The first event ensures that SendSingleMessage() is not blocking this
1065 // thread. The second event ensures that the message is processed.
1066 Event event_set_by_test_thread;
1067 Event event_set_by_background_thread;
1068 background_thread->PostTask(RTC_FROM_HERE,
1069 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1070 &event_set_by_background_thread));
1071 event_set_by_test_thread.Set();
1072 event_set_by_background_thread.Wait(Event::kForever);
1073}
1074
1075TEST(ThreadPostTaskTest, InvokesInPostedOrder) {
1076 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1077 background_thread->Start();
1078
1079 Event first;
1080 Event second;
1081 Event third;
1082 Event fourth;
1083
1084 background_thread->PostTask(RTC_FROM_HERE,
1085 Bind(&WaitAndSetEvent, &first, &second));
1086 background_thread->PostTask(RTC_FROM_HERE,
1087 Bind(&WaitAndSetEvent, &second, &third));
1088 background_thread->PostTask(RTC_FROM_HERE,
1089 Bind(&WaitAndSetEvent, &third, &fourth));
1090
1091 // All tasks have been posted before the first one is unblocked.
1092 first.Set();
1093 // Only if the chain is invoked in posted order will the last event be set.
1094 fourth.Wait(Event::kForever);
1095}
1096
Steve Antonbcc1a762019-12-11 11:21:53 -08001097TEST(ThreadPostDelayedTaskTest, InvokesAsynchronously) {
1098 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1099 background_thread->Start();
1100
1101 // The first event ensures that SendSingleMessage() is not blocking this
1102 // thread. The second event ensures that the message is processed.
1103 Event event_set_by_test_thread;
1104 Event event_set_by_background_thread;
1105 background_thread->PostDelayedTask(
1106 RTC_FROM_HERE,
1107 Bind(&WaitAndSetEvent, &event_set_by_test_thread,
1108 &event_set_by_background_thread),
1109 /*milliseconds=*/10);
1110 event_set_by_test_thread.Set();
1111 event_set_by_background_thread.Wait(Event::kForever);
1112}
1113
1114TEST(ThreadPostDelayedTaskTest, InvokesInDelayOrder) {
Steve Anton094396f2019-12-16 00:56:02 -08001115 ScopedFakeClock clock;
Steve Antonbcc1a762019-12-11 11:21:53 -08001116 std::unique_ptr<rtc::Thread> background_thread(rtc::Thread::Create());
1117 background_thread->Start();
1118
1119 Event first;
1120 Event second;
1121 Event third;
1122 Event fourth;
1123
1124 background_thread->PostDelayedTask(RTC_FROM_HERE,
1125 Bind(&WaitAndSetEvent, &third, &fourth),
1126 /*milliseconds=*/11);
1127 background_thread->PostDelayedTask(RTC_FROM_HERE,
1128 Bind(&WaitAndSetEvent, &first, &second),
1129 /*milliseconds=*/9);
1130 background_thread->PostDelayedTask(RTC_FROM_HERE,
1131 Bind(&WaitAndSetEvent, &second, &third),
1132 /*milliseconds=*/10);
1133
1134 // All tasks have been posted before the first one is unblocked.
1135 first.Set();
Steve Anton094396f2019-12-16 00:56:02 -08001136 // Only if the chain is invoked in delay order will the last event be set.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001137 clock.AdvanceTime(webrtc::TimeDelta::Millis(11));
Steve Anton094396f2019-12-16 00:56:02 -08001138 EXPECT_TRUE(fourth.Wait(0));
Steve Antonbcc1a762019-12-11 11:21:53 -08001139}
1140
Danil Chapovalov912b3b82019-11-22 15:52:40 +01001141class ThreadFactory : public webrtc::TaskQueueFactory {
1142 public:
1143 std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>
1144 CreateTaskQueue(absl::string_view /* name */,
1145 Priority /*priority*/) const override {
1146 std::unique_ptr<Thread> thread = Thread::Create();
1147 thread->Start();
1148 return std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter>(
1149 thread.release());
1150 }
1151};
1152
1153using ::webrtc::TaskQueueTest;
1154
1155INSTANTIATE_TEST_SUITE_P(RtcThread,
1156 TaskQueueTest,
1157 ::testing::Values(std::make_unique<ThreadFactory>));
1158
Mirko Bonadeie10b1632018-12-11 18:43:40 +01001159} // namespace
1160} // namespace rtc