blob: e7701e84b38e4ea54fb76099c336bd7b21b24745 [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
kjellandere96c45b2017-06-30 10:45:21 -070013#include "webrtc/rtc_base/asyncinvoker.h"
14#include "webrtc/rtc_base/asyncudpsocket.h"
15#include "webrtc/rtc_base/event.h"
16#include "webrtc/rtc_base/gunit.h"
tommie7251592017-07-14 14:44:46 -070017#include "webrtc/rtc_base/nullsocketserver.h"
kjellandere96c45b2017-06-30 10:45:21 -070018#include "webrtc/rtc_base/physicalsocketserver.h"
19#include "webrtc/rtc_base/sigslot.h"
20#include "webrtc/rtc_base/socketaddress.h"
21#include "webrtc/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) {}
47 virtual ~TestMessage() {}
48
49 int value;
50};
51
52// Receives on a socket and sends by posting messages.
53class SocketClient : public TestGenerator, public sigslot::has_slots<> {
54 public:
55 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
56 Thread* post_thread, MessageHandler* phandler)
57 : socket_(AsyncUDPSocket::Create(socket, addr)),
58 post_thread_(post_thread),
59 post_handler_(phandler) {
60 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
61 }
62
63 ~SocketClient() {
64 delete socket_;
65 }
66
67 SocketAddress address() const { return socket_->GetLocalAddress(); }
68
69 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
70 const SocketAddress& remote_addr,
71 const PacketTime& packet_time) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020072 EXPECT_EQ(size, sizeof(uint32_t));
73 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
74 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070076 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
77 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078 }
79
80 private:
81 AsyncUDPSocket* socket_;
82 Thread* post_thread_;
83 MessageHandler* post_handler_;
84};
85
86// Receives messages and sends on a socket.
87class MessageClient : public MessageHandler, public TestGenerator {
88 public:
89 MessageClient(Thread* pth, Socket* socket)
90 : socket_(socket) {
91 }
92
93 virtual ~MessageClient() {
94 delete socket_;
95 }
96
97 virtual void OnMessage(Message *pmsg) {
98 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
99 int result = Next(msg->value);
100 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
101 delete msg;
102 }
103
104 private:
105 Socket* socket_;
106};
107
deadbeefaea92932017-05-23 12:55:03 -0700108class CustomThread : public rtc::Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109 public:
tommie7251592017-07-14 14:44:46 -0700110 CustomThread()
111 : Thread(std::unique_ptr<SocketServer>(new rtc::NullSocketServer())) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112 virtual ~CustomThread() { Stop(); }
113 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000114
115 bool WrapCurrent() {
116 return Thread::WrapCurrent();
117 }
118 void UnwrapCurrent() {
119 Thread::UnwrapCurrent();
120 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121};
122
123
124// 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
132 virtual ~SignalWhenDestroyedThread() {
133 Stop();
134 event_->Set();
135 }
136
137 virtual void Run() {
138 // 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) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184 void operator()() { if (flag_) *flag_ = true; }
185 private:
nissed9b75be2015-11-16 00:54:07 -0800186 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187};
188struct FunctorC {
189 int operator()() {
190 Thread::Current()->ProcessMessages(50);
191 return 24;
192 }
193};
194
195// See: https://code.google.com/p/webrtc/issues/detail?id=2409
196TEST(ThreadTest, DISABLED_Main) {
197 const SocketAddress addr("127.0.0.1", 0);
198
199 // Create the messaging client on its own thread.
tommie7251592017-07-14 14:44:46 -0700200 auto th1 = Thread::CreateWithSocketServer();
201 Socket* socket =
202 th1->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
203 MessageClient msg_client(th1.get(), socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000204
205 // Create the socket client on its own thread.
tommie7251592017-07-14 14:44:46 -0700206 auto th2 = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207 AsyncSocket* asocket =
tommie7251592017-07-14 14:44:46 -0700208 th2->socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
209 SocketClient sock_client(asocket, addr, th1.get(), &msg_client);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000210
211 socket->Connect(sock_client.address());
212
tommie7251592017-07-14 14:44:46 -0700213 th1->Start();
214 th2->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215
216 // Get the messages started.
tommie7251592017-07-14 14:44:46 -0700217 th1->PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000218
219 // Give the clients a little while to run.
220 // Messages will be processed at 100, 300, 500, 700, 900.
221 Thread* th_main = Thread::Current();
222 th_main->ProcessMessages(1000);
223
224 // Stop the sending client. Give the receiver a bit longer to run, in case
225 // it is running on a machine that is under load (e.g. the build machine).
tommie7251592017-07-14 14:44:46 -0700226 th1->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000227 th_main->ProcessMessages(200);
tommie7251592017-07-14 14:44:46 -0700228 th2->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 // Make sure the results were correct
231 EXPECT_EQ(5, msg_client.count);
232 EXPECT_EQ(34, msg_client.last);
233 EXPECT_EQ(5, sock_client.count);
234 EXPECT_EQ(55, sock_client.last);
235}
236
237// Test that setting thread names doesn't cause a malfunction.
238// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000239TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 // Default name
tommie7251592017-07-14 14:44:46 -0700241 auto thread = Thread::CreateWithSocketServer();
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 // Name with no object parameter
tommie7251592017-07-14 14:44:46 -0700245 thread = Thread::CreateWithSocketServer();
deadbeef37f5ecf2017-02-27 14:06:41 -0800246 EXPECT_TRUE(thread->SetName("No object", nullptr));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 EXPECT_TRUE(thread->Start());
248 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 // Really long name
tommie7251592017-07-14 14:44:46 -0700250 thread = Thread::CreateWithSocketServer();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
252 EXPECT_TRUE(thread->Start());
253 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254}
255
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000256TEST(ThreadTest, Wrap) {
257 Thread* current_thread = Thread::Current();
258 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259 CustomThread* cthread = new CustomThread();
260 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000261 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 EXPECT_FALSE(cthread->IsOwned());
263 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000264 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000266 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267}
268
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000269TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700271 auto thread = Thread::CreateWithSocketServer();
272 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 // Try calling functors.
tommie7251592017-07-14 14:44:46 -0700274 EXPECT_EQ(42, thread->Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800275 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276 FunctorB f2(&called);
tommie7251592017-07-14 14:44:46 -0700277 thread->Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800278 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279 // Try calling bare functions.
280 struct LocalFuncs {
281 static int Func1() { return 999; }
282 static void Func2() {}
283 };
tommie7251592017-07-14 14:44:46 -0700284 EXPECT_EQ(999, thread->Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
285 thread->Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286}
287
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000288// Verifies that two threads calling Invoke on each other at the same time does
289// not deadlock.
290TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
291 AutoThread thread;
292 Thread* current_thread = Thread::Current();
deadbeef37f5ecf2017-02-27 14:06:41 -0800293 ASSERT_TRUE(current_thread != nullptr);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000294
tommie7251592017-07-14 14:44:46 -0700295 auto other_thread = Thread::CreateWithSocketServer();
296 other_thread->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000297
298 struct LocalFuncs {
299 static void Set(bool* out) { *out = true; }
300 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700301 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000302 }
303 };
304
305 bool called = false;
tommie7251592017-07-14 14:44:46 -0700306 other_thread->Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700307 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000308
309 EXPECT_TRUE(called);
310}
311
312// Verifies that if thread A invokes a call on thread B and thread C is trying
313// to invoke A at the same time, thread A does not handle C's invoke while
314// invoking B.
315TEST(ThreadTest, ThreeThreadsInvoke) {
316 AutoThread thread;
317 Thread* thread_a = Thread::Current();
tommie7251592017-07-14 14:44:46 -0700318 auto thread_b = Thread::CreateWithSocketServer();
319 auto thread_c = Thread::CreateWithSocketServer();
320 thread_b->Start();
321 thread_c->Start();
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000322
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000323 class LockedBool {
324 public:
325 explicit LockedBool(bool value) : value_(value) {}
326
327 void Set(bool value) {
328 CritScope lock(&crit_);
329 value_ = value;
330 }
331
332 bool Get() {
333 CritScope lock(&crit_);
334 return value_;
335 }
336
337 private:
338 CriticalSection crit_;
339 bool value_ GUARDED_BY(crit_);
340 };
341
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000342 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000343 static void Set(LockedBool* out) { out->Set(true); }
344 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700345 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000346 }
347
348 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000349 static void SetAndInvokeSet(LockedBool* out,
350 Thread* thread,
351 LockedBool* out_inner) {
352 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000353 InvokeSet(thread, out_inner);
354 }
355
356 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
357 // |thread1| starts the call.
deadbeef162cb532017-02-23 17:10:07 -0800358 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
359 Thread* thread1,
360 Thread* thread2,
361 LockedBool* out) {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000362 CriticalSection crit;
363 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000364
deadbeef162cb532017-02-23 17:10:07 -0800365 invoker->AsyncInvoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700366 RTC_FROM_HERE, thread1,
367 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000368
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000369 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000370 }
371 };
372
deadbeef162cb532017-02-23 17:10:07 -0800373 AsyncInvoker invoker;
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000374 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000375
376 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
377 // Thread B returns when C receives the call and C should be blocked until A
378 // starts to process messages.
tommie7251592017-07-14 14:44:46 -0700379 thread_b->Invoke<void>(RTC_FROM_HERE,
380 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
381 thread_c.get(), thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000382 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000383
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000384 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000385}
386
jbauch25d1f282016-02-05 00:25:02 -0800387// Set the name on a thread when the underlying QueueDestroyed signal is
388// triggered. This causes an error if the object is already partially
389// destroyed.
390class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
391 public:
392 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
393 thread->SignalQueueDestroyed.connect(
394 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
395 }
396
397 void OnQueueDestroyed() {
398 // Makes sure that if we access the Thread while it's being destroyed, that
399 // it doesn't cause a problem because the vtable has been modified.
400 thread_->SetName("foo", nullptr);
401 }
402
403 private:
404 Thread* thread_;
405};
406
407TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
tommie7251592017-07-14 14:44:46 -0700408 auto thread1 = Thread::CreateWithSocketServer();
409 SetNameOnSignalQueueDestroyedTester tester1(thread1.get());
410 thread1.reset();
jbauch25d1f282016-02-05 00:25:02 -0800411
412 Thread* thread2 = new AutoThread();
413 SetNameOnSignalQueueDestroyedTester tester2(thread2);
414 delete thread2;
jbauch25d1f282016-02-05 00:25:02 -0800415}
416
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000417class AsyncInvokeTest : public testing::Test {
418 public:
419 void IntCallback(int value) {
420 EXPECT_EQ(expected_thread_, Thread::Current());
421 int_value_ = value;
422 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000423 void SetExpectedThreadForIntCallback(Thread* thread) {
424 expected_thread_ = thread;
425 }
426
427 protected:
428 enum { kWaitTimeout = 1000 };
429 AsyncInvokeTest()
430 : int_value_(0),
deadbeef37f5ecf2017-02-27 14:06:41 -0800431 expected_thread_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000432
433 int int_value_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 Thread* expected_thread_;
435};
436
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000437TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000438 AsyncInvoker invoker;
439 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700440 auto thread = Thread::CreateWithSocketServer();
441 thread->Start();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000442 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800443 AtomicBool called;
tommie7251592017-07-14 14:44:46 -0700444 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800445 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
tommie7251592017-07-14 14:44:46 -0700446 thread->Stop();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447}
448
deadbeef162cb532017-02-23 17:10:07 -0800449TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
450 // Use these events to get in a state where the functor is in the middle of
451 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
452 // is run.
453 Event functor_started(false, false);
deadbeefaea92932017-05-23 12:55:03 -0700454 Event functor_continue(false, false);
deadbeef162cb532017-02-23 17:10:07 -0800455 Event functor_finished(false, false);
456
tommie7251592017-07-14 14:44:46 -0700457 auto thread = Thread::CreateWithSocketServer();
458 thread->Start();
deadbeef162cb532017-02-23 17:10:07 -0800459 volatile bool invoker_destroyed = false;
460 {
deadbeef3af63b02017-08-08 17:59:47 -0700461 auto functor = [&functor_started, &functor_continue, &functor_finished,
462 &invoker_destroyed] {
463 functor_started.Set();
464 functor_continue.Wait(Event::kForever);
465 rtc::Thread::Current()->SleepMs(kWaitTimeout);
466 EXPECT_FALSE(invoker_destroyed);
467 functor_finished.Set();
468 };
deadbeef162cb532017-02-23 17:10:07 -0800469 AsyncInvoker invoker;
deadbeef3af63b02017-08-08 17:59:47 -0700470 invoker.AsyncInvoke<void>(RTC_FROM_HERE, thread.get(), functor);
deadbeef162cb532017-02-23 17:10:07 -0800471 functor_started.Wait(Event::kForever);
deadbeefaea92932017-05-23 12:55:03 -0700472
deadbeef3af63b02017-08-08 17:59:47 -0700473 // Destroy the invoker while the functor is still executing (doing
474 // SleepMs).
deadbeefaea92932017-05-23 12:55:03 -0700475 functor_continue.Set();
deadbeef162cb532017-02-23 17:10:07 -0800476 }
477
478 // If the destructor DIDN'T wait for the functor to finish executing, it will
479 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
480 // second.
481 invoker_destroyed = true;
482 functor_finished.Wait(Event::kForever);
483}
484
deadbeef3af63b02017-08-08 17:59:47 -0700485// Variant of the above test where the async-invoked task calls AsyncInvoke
486// *again*, for the thread on which the AsyncInvoker is currently being
487// destroyed. This shouldn't deadlock or crash; this second invocation should
488// just be ignored.
489TEST_F(AsyncInvokeTest, KillInvokerDuringExecuteWithReentrantInvoke) {
490 Event functor_started(false, false);
491 // Flag used to verify that the recursively invoked task never actually runs.
492 bool reentrant_functor_run = false;
493
494 Thread* main = Thread::Current();
495 Thread thread;
496 thread.Start();
497 {
498 AsyncInvoker invoker;
499 auto reentrant_functor = [&reentrant_functor_run] {
500 reentrant_functor_run = true;
501 };
502 auto functor = [&functor_started, &invoker, main, reentrant_functor] {
503 functor_started.Set();
504 Thread::Current()->SleepMs(kWaitTimeout);
505 invoker.AsyncInvoke<void>(RTC_FROM_HERE, main, reentrant_functor);
506 };
507 // This queues a task on |thread| to sleep for |kWaitTimeout| then queue a
508 // task on |main|. But this second queued task should never run, since the
509 // destructor will be entered before it's even invoked.
510 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, functor);
511 functor_started.Wait(Event::kForever);
512 }
513 EXPECT_FALSE(reentrant_functor_run);
514}
515
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000516TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800518 AtomicBool flag1;
519 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000520 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700521 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
522 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000523 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800524 EXPECT_FALSE(flag1.get());
525 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 // Force them to run now.
527 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800528 EXPECT_TRUE(flag1.get());
529 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000530}
531
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000532TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800534 AtomicBool flag1;
535 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700537 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700539 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800541 EXPECT_FALSE(flag1.get());
542 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543 // Execute pending calls with id == 5.
544 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800545 EXPECT_TRUE(flag1.get());
546 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547 flag1 = false;
548 // Execute all pending calls. The id == 5 call should not execute again.
549 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800550 EXPECT_FALSE(flag1.get());
551 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000552}
553
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200554class GuardedAsyncInvokeTest : public testing::Test {
555 public:
556 void IntCallback(int value) {
557 EXPECT_EQ(expected_thread_, Thread::Current());
558 int_value_ = value;
559 }
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200560 void SetExpectedThreadForIntCallback(Thread* thread) {
561 expected_thread_ = thread;
562 }
563
564 protected:
565 const static int kWaitTimeout = 1000;
566 GuardedAsyncInvokeTest()
567 : int_value_(0),
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200568 expected_thread_(nullptr) {}
569
570 int int_value_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200571 Thread* expected_thread_;
572};
573
574// Functor for creating an invoker.
575struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700576 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
577 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200578 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700579 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200580};
581
582// Test that we can call AsyncInvoke<void>() after the thread died.
583TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
584 // Create and start the thread.
tommie7251592017-07-14 14:44:46 -0700585 std::unique_ptr<Thread> thread(Thread::Create());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200586 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700587 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200588 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700589 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200590 // Kill |thread|.
591 thread = nullptr;
592 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800593 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700594 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200595 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800596 WAIT(called.get(), kWaitTimeout);
597 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200598}
599
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200600// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
601// when Thread is still alive.
602TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
603 GuardedAsyncInvoker invoker;
604 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800605 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700606 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800607 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200608}
609
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200610TEST_F(GuardedAsyncInvokeTest, Flush) {
611 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800612 AtomicBool flag1;
613 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200614 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700615 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
616 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200617 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800618 EXPECT_FALSE(flag1.get());
619 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200620 // Force them to run now.
621 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800622 EXPECT_TRUE(flag1.get());
623 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200624}
625
626TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
627 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800628 AtomicBool flag1;
629 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200630 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700631 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
632 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200633 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800634 EXPECT_FALSE(flag1.get());
635 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200636 // Execute pending calls with id == 5.
637 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800638 EXPECT_TRUE(flag1.get());
639 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200640 flag1 = false;
641 // Execute all pending calls. The id == 5 call should not execute again.
642 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800643 EXPECT_FALSE(flag1.get());
644 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200645}