blob: 5f00064eb174a4764751944238eeee1d77ba506d [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
kwibergbfefb032016-05-01 14:53:46 -070011#include <memory>
12
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020013#include "rtc_base/asyncinvoker.h"
14#include "rtc_base/asyncudpsocket.h"
15#include "rtc_base/event.h"
16#include "rtc_base/gunit.h"
17#include "rtc_base/nullsocketserver.h"
18#include "rtc_base/physicalsocketserver.h"
19#include "rtc_base/sigslot.h"
20#include "rtc_base/socketaddress.h"
21#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
23#if defined(WEBRTC_WIN)
24#include <comdef.h> // NOLINT
25#endif
26
27using namespace rtc;
28
29// Generates a sequence of numbers (collaboratively).
30class TestGenerator {
31 public:
32 TestGenerator() : last(0), count(0) {}
33
34 int Next(int prev) {
35 int result = prev + last;
36 last = result;
37 count += 1;
38 return result;
39 }
40
41 int last;
42 int count;
43};
44
45struct TestMessage : public MessageData {
46 explicit TestMessage(int v) : value(v) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047
48 int value;
49};
50
51// Receives on a socket and sends by posting messages.
52class SocketClient : public TestGenerator, public sigslot::has_slots<> {
53 public:
54 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
55 Thread* post_thread, MessageHandler* phandler)
56 : socket_(AsyncUDPSocket::Create(socket, addr)),
57 post_thread_(post_thread),
58 post_handler_(phandler) {
59 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
60 }
61
Steve Anton9de3aac2017-10-24 10:08:26 -070062 ~SocketClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
64 SocketAddress address() const { return socket_->GetLocalAddress(); }
65
66 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
67 const SocketAddress& remote_addr,
68 const PacketTime& packet_time) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020069 EXPECT_EQ(size, sizeof(uint32_t));
70 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
71 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070073 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
74 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075 }
76
77 private:
78 AsyncUDPSocket* socket_;
79 Thread* post_thread_;
80 MessageHandler* post_handler_;
81};
82
83// Receives messages and sends on a socket.
84class MessageClient : public MessageHandler, public TestGenerator {
85 public:
86 MessageClient(Thread* pth, Socket* socket)
87 : socket_(socket) {
88 }
89
Steve Anton9de3aac2017-10-24 10:08:26 -070090 ~MessageClient() override { delete socket_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091
Steve Anton9de3aac2017-10-24 10:08:26 -070092 void OnMessage(Message* pmsg) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
94 int result = Next(msg->value);
95 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
96 delete msg;
97 }
98
99 private:
100 Socket* socket_;
101};
102
deadbeefaea92932017-05-23 12:55:03 -0700103class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 public:
tommie7251592017-07-14 14:44:46 -0700105 CustomThread()
106 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
Steve Anton9de3aac2017-10-24 10:08:26 -0700107 ~CustomThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000109
110 bool WrapCurrent() {
111 return Thread::WrapCurrent();
112 }
113 void UnwrapCurrent() {
114 Thread::UnwrapCurrent();
115 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116};
117
118
119// A thread that does nothing when it runs and signals an event
120// when it is destroyed.
121class SignalWhenDestroyedThread : public Thread {
122 public:
123 SignalWhenDestroyedThread(Event* event)
tommie7251592017-07-14 14:44:46 -0700124 : Thread(std::unique_ptr<SocketServer>(new NullSocketServer())),
125 event_(event) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126
Steve Anton9de3aac2017-10-24 10:08:26 -0700127 ~SignalWhenDestroyedThread() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128 Stop();
129 event_->Set();
130 }
131
Steve Anton9de3aac2017-10-24 10:08:26 -0700132 void Run() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133 // Do nothing.
134 }
135
136 private:
137 Event* event_;
138};
139
nissed9b75be2015-11-16 00:54:07 -0800140// A bool wrapped in a mutex, to avoid data races. Using a volatile
141// bool should be sufficient for correct code ("eventual consistency"
142// between caches is sufficient), but we can't tell the compiler about
143// that, and then tsan complains about a data race.
144
145// See also discussion at
146// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
147
148// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
149// the right thing to do, but those features are not yet allowed. Or
deadbeefaea92932017-05-23 12:55:03 -0700150// rtc::AtomicInt, if/when that is added. Since the use isn't
nissed9b75be2015-11-16 00:54:07 -0800151// performance critical, use a plain critical section for the time
152// being.
153
154class AtomicBool {
155 public:
156 explicit AtomicBool(bool value = false) : flag_(value) {}
157 AtomicBool& operator=(bool value) {
158 CritScope scoped_lock(&cs_);
159 flag_ = value;
160 return *this;
161 }
162 bool get() const {
163 CritScope scoped_lock(&cs_);
164 return flag_;
165 }
166
167 private:
pbos5ad935c2016-01-25 03:52:44 -0800168 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800169 bool flag_;
170};
171
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172// Function objects to test Thread::Invoke.
173struct FunctorA {
174 int operator()() { return 42; }
175};
176class FunctorB {
177 public:
nissed9b75be2015-11-16 00:54:07 -0800178 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 void operator()() { if (flag_) *flag_ = true; }
180 private:
nissed9b75be2015-11-16 00:54:07 -0800181 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182};
183struct FunctorC {
184 int operator()() {
185 Thread::Current()->ProcessMessages(50);
186 return 24;
187 }
188};
189
190// See: https://code.google.com/p/webrtc/issues/detail?id=2409
191TEST(ThreadTest, DISABLED_Main) {
192 const SocketAddress addr("127.0.0.1", 0);
193
194 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700195 auto th1 = Thread::CreateWithSocketServer();
196 Socket* socket =
197 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
198 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
200 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700201 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700203 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
204 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205
206 socket->Connect(sock_client.address());
207
tommie7251592017-07-14 14:44:46 -0700208 th1->Start();
209 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210
211 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700212 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213
214 // Give the clients a little while to run.
215 // Messages will be processed at 100, 300, 500, 700, 900.
216 Thread* th_main = Thread::Current();
217 th_main->ProcessMessages(1000);
218
219 // Stop the sending client. Give the receiver a bit longer to run, in case
220 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700221 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700223 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224
225 // Make sure the results were correct
226 EXPECT_EQ(5, msg_client.count);
227 EXPECT_EQ(34, msg_client.last);
228 EXPECT_EQ(5, sock_client.count);
229 EXPECT_EQ(55, sock_client.last);
230}
231
232// Test that setting thread names doesn't cause a malfunction.
233// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000234TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235 // Default name
tommie7251592017-07-14 14:44:46 -0700236 auto thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237 EXPECT_TRUE(thread->Start());
238 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700240 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800241 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242 EXPECT_TRUE(thread->Start());
243 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000244 // Really long name
tommie7251592017-07-14 14:44:46 -0700245 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
247 EXPECT_TRUE(thread->Start());
248 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249}
250
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000251TEST(ThreadTest, Wrap) {
252 Thread* current_thread = Thread::Current();
253 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 CustomThread* cthread = new CustomThread();
255 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000256 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257 EXPECT_FALSE(cthread->IsOwned());
258 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000259 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000261 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262}
263
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000264TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700266 auto thread = Thread::CreateWithSocketServer();
267 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700269 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800270 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700272 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800273 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274 // Try calling bare functions.
275 struct LocalFuncs {
276 static int Func1() { return 999; }
277 static void Func2() {}
278 };
tommie7251592017-07-14 14:44:46 -0700279 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
280 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281}
282
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000283// Verifies that two threads calling Invoke on each other at the same time does
284// not deadlock.
285TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
286 AutoThread thread;
287 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800288 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000289
tommie7251592017-07-14 14:44:46 -0700290 auto other_thread = Thread::CreateWithSocketServer();
291 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000292
293 struct LocalFuncs {
294 static void Set(bool* out) { *out = true; }
295 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700296 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000297 }
298 };
299
300 bool called = false;
tommie7251592017-07-14 14:44:46 -0700301 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700302 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000303
304 EXPECT_TRUE(called);
305}
306
307// Verifies that if thread A invokes a call on thread B and thread C is trying
308// to invoke A at the same time, thread A does not handle C's invoke while
309// invoking B.
310TEST(ThreadTest, ThreeThreadsInvoke) {
311 AutoThread thread;
312 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700313 auto thread_b = Thread::CreateWithSocketServer();
314 auto thread_c = Thread::CreateWithSocketServer();
315 thread_b->Start();
316 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000317
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000318 class LockedBool {
319 public:
320 explicit LockedBool(bool value) : value_(value) {}
321
322 void Set(bool value) {
323 CritScope lock(&crit_);
324 value_ = value;
325 }
326
327 bool Get() {
328 CritScope lock(&crit_);
329 return value_;
330 }
331
332 private:
333 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700334 bool value_ RTC_GUARDED_BY(crit_);
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000335 };
336
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000337 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000338 static void Set(LockedBool* out) { out->Set(true); }
339 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700340 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000341 }
342
343 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000344 static void SetAndInvokeSet(LockedBool* out,
345 Thread* thread,
346 LockedBool* out_inner) {
347 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000348 InvokeSet(thread, out_inner);
349 }
350
351 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
352 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800353 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
354 Thread* thread1,
355 Thread* thread2,
356 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000357 CriticalSection crit;
358 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000359
deadbeef162cb532017-02-23 17:10:07 -0800360 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700361 RTC_FROM_HERE, thread1,
362 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000363
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000364 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000365 }
366 };
367
deadbeef162cb532017-02-23 17:10:07 -0800368 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000369 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000370
371 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
372 // Thread B returns when C receives the call and C should be blocked until A
373 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700374 thread_b->Invoke<void>(RTC_FROM_HERE,
375 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
376 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000377 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000378
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000379 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000380}
381
jbauch25d1f282016-02-05 00:25:02 -0800382// Set the name on a thread when the underlying QueueDestroyed signal is
383// triggered. This causes an error if the object is already partially
384// destroyed.
385class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
386 public:
387 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
388 thread->SignalQueueDestroyed.connect(
389 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
390 }
391
392 void OnQueueDestroyed() {
393 // Makes sure that if we access the Thread while it's being destroyed, that
394 // it doesn't cause a problem because the vtable has been modified.
395 thread_->SetName("foo", nullptr);
396 }
397
398 private:
399 Thread* thread_;
400};
401
402TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700403 auto thread1 = Thread::CreateWithSocketServer();
404 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
405 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800406
407 Thread* thread2 = new AutoThread();
408 SetNameOnSignalQueueDestroyedTester tester2(thread2);
409 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800410}
411
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412class AsyncInvokeTest : public testing::Test {
413 public:
414 void IntCallback(int value) {
415 EXPECT_EQ(expected_thread_, Thread::Current());
416 int_value_ = value;
417 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418 void SetExpectedThreadForIntCallback(Thread* thread) {
419 expected_thread_ = thread;
420 }
421
422 protected:
423 enum { kWaitTimeout = 1000 };
424 AsyncInvokeTest()
425 : int_value_(0),
deadbeef37f5ecf2017-02-27 14:06:41 -0800426 expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427
428 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429 Thread* expected_thread_;
430};
431
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000432TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 AsyncInvoker invoker;
434 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700435 auto thread = Thread::CreateWithSocketServer();
436 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800438 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700439 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800440 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700441 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000442}
443
deadbeef162cb532017-02-23 17:10:07 -0800444TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
445 // Use these events to get in a state where the functor is in the middle of
446 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
447 // is run.
448 Event functor_started(false, false);
deadbeefaea92932017-05-23 12:55:03 -0700449 Event functor_continue(false, false);
deadbeef162cb532017-02-23 17:10:07 -0800450 Event functor_finished(false, false);
451
tommie7251592017-07-14 14:44:46 -0700452 auto thread = Thread::CreateWithSocketServer();
453 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800454 volatile bool invoker_destroyed = false;
455 {
deadbeef3af63b02017-08-08 17:59:47 -0700456 auto functor = [&functor_started, &functor_continue, &functor_finished,
457 &invoker_destroyed] {
458 functor_started.Set();
459 functor_continue.Wait(Event::kForever);
460 rtc::Thread::Current()->SleepMs(kWaitTimeout);
461 EXPECT_FALSE(invoker_destroyed);
462 functor_finished.Set();
463 };
deadbeef162cb532017-02-23 17:10:07 -0800464 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700465 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800466 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700467
deadbeef3af63b02017-08-08 17:59:47 -0700468 // Destroy the invoker while the functor is still executing (doing
469 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700470 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800471 }
472
473 // If the destructor DIDN'T wait for the functor to finish executing, it will
474 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
475 // second.
476 invoker_destroyed = true;
477 functor_finished.Wait(Event::kForever);
478}
479
deadbeef3af63b02017-08-08 17:59:47 -0700480// Variant of the above test where the async-invoked task calls AsyncInvoke
481// *again*, for the thread on which the AsyncInvoker is currently being
482// destroyed. This shouldn't deadlock or crash; this second invocation should
483// just be ignored.
484TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
485 Event functor_started(false, false);
486 // Flag used to verify that the recursively invoked task never actually runs.
487 bool reentrant_functor_run = false;
488
489 Thread* main = Thread::Current();
490 Thread thread;
491 thread.Start();
492 {
493 AsyncInvoker invoker;
494 auto reentrant_functor = [&reentrant_functor_run] {
495 reentrant_functor_run = true;
496 };
497 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
498 functor_started.Set();
499 Thread::Current()->SleepMs(kWaitTimeout);
500 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
501 };
502 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
503 // task on |main|. But this second queued task should never run, since the
504 // destructor will be entered before it's even invoked.
505 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
506 functor_started.Wait(Event::kForever);
507 }
508 EXPECT_FALSE(reentrant_functor_run);
509}
510
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000511TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800513 AtomicBool flag1;
514 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000515 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700516 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
517 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800519 EXPECT_FALSE(flag1.get());
520 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 // Force them to run now.
522 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800523 EXPECT_TRUE(flag1.get());
524 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525}
526
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000527TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800529 AtomicBool flag1;
530 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700532 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700534 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800536 EXPECT_FALSE(flag1.get());
537 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538 // Execute pending calls with id == 5.
539 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800540 EXPECT_TRUE(flag1.get());
541 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542 flag1 = false;
543 // Execute all pending calls. The id == 5 call should not execute again.
544 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800545 EXPECT_FALSE(flag1.get());
546 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547}
548
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200549class GuardedAsyncInvokeTest : public testing::Test {
550 public:
551 void IntCallback(int value) {
552 EXPECT_EQ(expected_thread_, Thread::Current());
553 int_value_ = value;
554 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200555 void SetExpectedThreadForIntCallback(Thread* thread) {
556 expected_thread_ = thread;
557 }
558
559 protected:
560 const static int kWaitTimeout = 1000;
561 GuardedAsyncInvokeTest()
562 : int_value_(0),
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200563 expected_thread_(nullptr) {}
564
565 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200566 Thread* expected_thread_;
567};
568
569// Functor for creating an invoker.
570struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700571 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
572 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200573 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700574 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200575};
576
577// Test that we can call AsyncInvoke<void>() after the thread died.
578TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
579 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700580 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200581 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700582 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200583 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700584 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200585 // Kill |thread|.
586 thread = nullptr;
587 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800588 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700589 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200590 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800591 WAIT(called.get(), kWaitTimeout);
592 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200593}
594
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200595// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
596// when Thread is still alive.
597TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
598 GuardedAsyncInvoker invoker;
599 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800600 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700601 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800602 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200603}
604
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200605TEST_F(GuardedAsyncInvokeTest, Flush) {
606 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800607 AtomicBool flag1;
608 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200609 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700610 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
611 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200612 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800613 EXPECT_FALSE(flag1.get());
614 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200615 // Force them to run now.
616 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800617 EXPECT_TRUE(flag1.get());
618 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200619}
620
621TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
622 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800623 AtomicBool flag1;
624 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200625 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700626 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
627 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200628 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800629 EXPECT_FALSE(flag1.get());
630 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200631 // Execute pending calls with id == 5.
632 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800633 EXPECT_TRUE(flag1.get());
634 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200635 flag1 = false;
636 // Execute all pending calls. The id == 5 call should not execute again.
637 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800638 EXPECT_FALSE(flag1.get());
639 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200640}