blob: bf3cbd0896341354e11db1fd9b7f1d0abb718398 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#include "webrtc/base/asyncinvoker.h"
14#include "webrtc/base/asyncudpsocket.h"
15#include "webrtc/base/event.h"
16#include "webrtc/base/gunit.h"
17#include "webrtc/base/physicalsocketserver.h"
jbauch25d1f282016-02-05 00:25:02 -080018#include "webrtc/base/sigslot.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include "webrtc/base/socketaddress.h"
20#include "webrtc/base/thread.h"
21
22#if defined(WEBRTC_WIN)
23#include <comdef.h> // NOLINT
24#endif
25
26using namespace rtc;
27
28// Generates a sequence of numbers (collaboratively).
29class TestGenerator {
30 public:
31 TestGenerator() : last(0), count(0) {}
32
33 int Next(int prev) {
34 int result = prev + last;
35 last = result;
36 count += 1;
37 return result;
38 }
39
40 int last;
41 int count;
42};
43
44struct TestMessage : public MessageData {
45 explicit TestMessage(int v) : value(v) {}
46 virtual ~TestMessage() {}
47
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
62 ~SocketClient() {
63 delete socket_;
64 }
65
66 SocketAddress address() const { return socket_->GetLocalAddress(); }
67
68 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
69 const SocketAddress& remote_addr,
70 const PacketTime& packet_time) {
Peter Boström0c4e06b2015-10-07 12:23:21 +020071 EXPECT_EQ(size, sizeof(uint32_t));
72 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
73 uint32_t result = Next(prev);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074
75 post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
76 }
77
78 private:
79 AsyncUDPSocket* socket_;
80 Thread* post_thread_;
81 MessageHandler* post_handler_;
82};
83
84// Receives messages and sends on a socket.
85class MessageClient : public MessageHandler, public TestGenerator {
86 public:
87 MessageClient(Thread* pth, Socket* socket)
88 : socket_(socket) {
89 }
90
91 virtual ~MessageClient() {
92 delete socket_;
93 }
94
95 virtual void OnMessage(Message *pmsg) {
96 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
97 int result = Next(msg->value);
98 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
99 delete msg;
100 }
101
102 private:
103 Socket* socket_;
104};
105
106class CustomThread : public rtc::Thread {
107 public:
108 CustomThread() {}
109 virtual ~CustomThread() { Stop(); }
110 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000111
112 bool WrapCurrent() {
113 return Thread::WrapCurrent();
114 }
115 void UnwrapCurrent() {
116 Thread::UnwrapCurrent();
117 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118};
119
120
121// A thread that does nothing when it runs and signals an event
122// when it is destroyed.
123class SignalWhenDestroyedThread : public Thread {
124 public:
125 SignalWhenDestroyedThread(Event* event)
126 : event_(event) {
127 }
128
129 virtual ~SignalWhenDestroyedThread() {
130 Stop();
131 event_->Set();
132 }
133
134 virtual void Run() {
135 // Do nothing.
136 }
137
138 private:
139 Event* event_;
140};
141
nissed9b75be2015-11-16 00:54:07 -0800142// A bool wrapped in a mutex, to avoid data races. Using a volatile
143// bool should be sufficient for correct code ("eventual consistency"
144// between caches is sufficient), but we can't tell the compiler about
145// that, and then tsan complains about a data race.
146
147// See also discussion at
148// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
149
150// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
151// the right thing to do, but those features are not yet allowed. Or
152// rtc::AtomicInt, if/when that is added. Since the use isn't
153// performance critical, use a plain critical section for the time
154// being.
155
156class AtomicBool {
157 public:
158 explicit AtomicBool(bool value = false) : flag_(value) {}
159 AtomicBool& operator=(bool value) {
160 CritScope scoped_lock(&cs_);
161 flag_ = value;
162 return *this;
163 }
164 bool get() const {
165 CritScope scoped_lock(&cs_);
166 return flag_;
167 }
168
169 private:
pbos5ad935c2016-01-25 03:52:44 -0800170 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800171 bool flag_;
172};
173
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000174// Function objects to test Thread::Invoke.
175struct FunctorA {
176 int operator()() { return 42; }
177};
178class FunctorB {
179 public:
nissed9b75be2015-11-16 00:54:07 -0800180 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181 void operator()() { if (flag_) *flag_ = true; }
182 private:
nissed9b75be2015-11-16 00:54:07 -0800183 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184};
185struct FunctorC {
186 int operator()() {
187 Thread::Current()->ProcessMessages(50);
188 return 24;
189 }
190};
191
192// See: https://code.google.com/p/webrtc/issues/detail?id=2409
193TEST(ThreadTest, DISABLED_Main) {
194 const SocketAddress addr("127.0.0.1", 0);
195
196 // Create the messaging client on its own thread.
197 Thread th1;
198 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
199 SOCK_DGRAM);
200 MessageClient msg_client(&th1, socket);
201
202 // Create the socket client on its own thread.
203 Thread th2;
204 AsyncSocket* asocket =
205 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
206 SocketClient sock_client(asocket, addr, &th1, &msg_client);
207
208 socket->Connect(sock_client.address());
209
210 th1.Start();
211 th2.Start();
212
213 // Get the messages started.
214 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
215
216 // Give the clients a little while to run.
217 // Messages will be processed at 100, 300, 500, 700, 900.
218 Thread* th_main = Thread::Current();
219 th_main->ProcessMessages(1000);
220
221 // Stop the sending client. Give the receiver a bit longer to run, in case
222 // it is running on a machine that is under load (e.g. the build machine).
223 th1.Stop();
224 th_main->ProcessMessages(200);
225 th2.Stop();
226
227 // Make sure the results were correct
228 EXPECT_EQ(5, msg_client.count);
229 EXPECT_EQ(34, msg_client.last);
230 EXPECT_EQ(5, sock_client.count);
231 EXPECT_EQ(55, sock_client.last);
232}
233
234// Test that setting thread names doesn't cause a malfunction.
235// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000236TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237 // Default name
238 Thread *thread;
239 thread = new Thread();
240 EXPECT_TRUE(thread->Start());
241 thread->Stop();
242 delete thread;
243 thread = new Thread();
244 // Name with no object parameter
245 EXPECT_TRUE(thread->SetName("No object", NULL));
246 EXPECT_TRUE(thread->Start());
247 thread->Stop();
248 delete thread;
249 // Really long name
250 thread = new Thread();
251 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
252 EXPECT_TRUE(thread->Start());
253 thread->Stop();
254 delete thread;
255}
256
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000257TEST(ThreadTest, Wrap) {
258 Thread* current_thread = Thread::Current();
259 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 CustomThread* cthread = new CustomThread();
261 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000262 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263 EXPECT_FALSE(cthread->IsOwned());
264 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000265 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000267 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268}
269
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000270TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 // Create and start the thread.
272 Thread thread;
273 thread.Start();
274 // Try calling functors.
275 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800276 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 FunctorB f2(&called);
278 thread.Invoke<void>(f2);
nissed9b75be2015-11-16 00:54:07 -0800279 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280 // Try calling bare functions.
281 struct LocalFuncs {
282 static int Func1() { return 999; }
283 static void Func2() {}
284 };
285 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
286 thread.Invoke<void>(&LocalFuncs::Func2);
287}
288
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000289// Verifies that two threads calling Invoke on each other at the same time does
290// not deadlock.
291TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
292 AutoThread thread;
293 Thread* current_thread = Thread::Current();
294 ASSERT_TRUE(current_thread != NULL);
295
296 Thread other_thread;
297 other_thread.Start();
298
299 struct LocalFuncs {
300 static void Set(bool* out) { *out = true; }
301 static void InvokeSet(Thread* thread, bool* out) {
302 thread->Invoke<void>(Bind(&Set, out));
303 }
304 };
305
306 bool called = false;
307 other_thread.Invoke<void>(
308 Bind(&LocalFuncs::InvokeSet, current_thread, &called));
309
310 EXPECT_TRUE(called);
311}
312
313// Verifies that if thread A invokes a call on thread B and thread C is trying
314// to invoke A at the same time, thread A does not handle C's invoke while
315// invoking B.
316TEST(ThreadTest, ThreeThreadsInvoke) {
317 AutoThread thread;
318 Thread* thread_a = Thread::Current();
319 Thread thread_b, thread_c;
320 thread_b.Start();
321 thread_c.Start();
322
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) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000345 thread->Invoke<void>(Bind(&Set, out));
346 }
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.
358 static void AsyncInvokeSetAndWait(
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000359 Thread* thread1, Thread* thread2, LockedBool* out) {
360 CriticalSection crit;
361 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000362
363 AsyncInvoker invoker;
364 invoker.AsyncInvoke<void>(
365 thread1, Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
366
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000367 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000368 }
369 };
370
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000371 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000372
373 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
374 // Thread B returns when C receives the call and C should be blocked until A
375 // starts to process messages.
376 thread_b.Invoke<void>(Bind(&LocalFuncs::AsyncInvokeSetAndWait,
377 &thread_c, thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000378 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000379
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000380 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000381}
382
jbauch25d1f282016-02-05 00:25:02 -0800383// Set the name on a thread when the underlying QueueDestroyed signal is
384// triggered. This causes an error if the object is already partially
385// destroyed.
386class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
387 public:
388 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
389 thread->SignalQueueDestroyed.connect(
390 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
391 }
392
393 void OnQueueDestroyed() {
394 // Makes sure that if we access the Thread while it's being destroyed, that
395 // it doesn't cause a problem because the vtable has been modified.
396 thread_->SetName("foo", nullptr);
397 }
398
399 private:
400 Thread* thread_;
401};
402
403TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
404 Thread* thread1 = new Thread();
405 SetNameOnSignalQueueDestroyedTester tester1(thread1);
406 delete thread1;
407
408 Thread* thread2 = new AutoThread();
409 SetNameOnSignalQueueDestroyedTester tester2(thread2);
410 delete thread2;
411
412#if defined(WEBRTC_WIN)
413 Thread* thread3 = new ComThread();
414 SetNameOnSignalQueueDestroyedTester tester3(thread3);
415 delete thread3;
416#endif
417}
418
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000419class AsyncInvokeTest : public testing::Test {
420 public:
421 void IntCallback(int value) {
422 EXPECT_EQ(expected_thread_, Thread::Current());
423 int_value_ = value;
424 }
425 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
426 expected_thread_ = thread;
427 invoker->AsyncInvoke(thread, FunctorC(),
428 &AsyncInvokeTest::IntCallback,
429 static_cast<AsyncInvokeTest*>(this));
430 invoke_started_.Set();
431 }
432 void SetExpectedThreadForIntCallback(Thread* thread) {
433 expected_thread_ = thread;
434 }
435
436 protected:
437 enum { kWaitTimeout = 1000 };
438 AsyncInvokeTest()
439 : int_value_(0),
440 invoke_started_(true, false),
441 expected_thread_(NULL) {}
442
443 int int_value_;
444 Event invoke_started_;
445 Thread* expected_thread_;
446};
447
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000448TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449 AsyncInvoker invoker;
450 // Create and start the thread.
451 Thread thread;
452 thread.Start();
453 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800454 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800456 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000457}
458
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000459TEST_F(AsyncInvokeTest, WithCallback) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000460 AsyncInvoker invoker;
461 // Create and start the thread.
462 Thread thread;
463 thread.Start();
464 // Try calling functor.
465 SetExpectedThreadForIntCallback(Thread::Current());
466 invoker.AsyncInvoke(&thread, FunctorA(),
467 &AsyncInvokeTest::IntCallback,
468 static_cast<AsyncInvokeTest*>(this));
469 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
470}
471
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000472TEST_F(AsyncInvokeTest, CancelInvoker) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000473 // Create and start the thread.
474 Thread thread;
475 thread.Start();
476 // Try destroying invoker during call.
477 {
478 AsyncInvoker invoker;
479 invoker.AsyncInvoke(&thread, FunctorC(),
480 &AsyncInvokeTest::IntCallback,
481 static_cast<AsyncInvokeTest*>(this));
482 }
483 // With invoker gone, callback should be cancelled.
484 Thread::Current()->ProcessMessages(kWaitTimeout);
485 EXPECT_EQ(0, int_value_);
486}
487
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000488TEST_F(AsyncInvokeTest, CancelCallingThread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000489 AsyncInvoker invoker;
490 { // Create and start the thread.
491 Thread thread;
492 thread.Start();
493 // Try calling functor.
494 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
495 static_cast<AsyncInvokeTest*>(this),
496 &invoker, Thread::Current()));
497 // Wait for the call to begin.
498 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
499 }
500 // Calling thread is gone. Return message shouldn't happen.
501 Thread::Current()->ProcessMessages(kWaitTimeout);
502 EXPECT_EQ(0, int_value_);
503}
504
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000505TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506 Thread thread;
507 thread.Start();
508 {
509 AsyncInvoker invoker;
510 // Try calling functor.
511 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
512 static_cast<AsyncInvokeTest*>(this),
513 &invoker, Thread::Current()));
514 // Wait for the call to begin.
515 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
516 }
517 // Invoker is destroyed. Function should not execute.
518 Thread::Current()->ProcessMessages(kWaitTimeout);
519 EXPECT_EQ(0, int_value_);
520}
521
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000522TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000523 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800524 AtomicBool flag1;
525 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 // Queue two async calls to the current thread.
527 invoker.AsyncInvoke<void>(Thread::Current(),
528 FunctorB(&flag1));
529 invoker.AsyncInvoke<void>(Thread::Current(),
530 FunctorB(&flag2));
531 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800532 EXPECT_FALSE(flag1.get());
533 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 // Force them to run now.
535 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800536 EXPECT_TRUE(flag1.get());
537 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538}
539
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000540TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800542 AtomicBool flag1;
543 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 // Queue two async calls to the current thread, one with a message id.
545 invoker.AsyncInvoke<void>(Thread::Current(),
546 FunctorB(&flag1),
547 5);
548 invoker.AsyncInvoke<void>(Thread::Current(),
549 FunctorB(&flag2));
550 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800551 EXPECT_FALSE(flag1.get());
552 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000553 // Execute pending calls with id == 5.
554 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800555 EXPECT_TRUE(flag1.get());
556 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557 flag1 = false;
558 // Execute all pending calls. The id == 5 call should not execute again.
559 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800560 EXPECT_FALSE(flag1.get());
561 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000562}
563
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200564class GuardedAsyncInvokeTest : public testing::Test {
565 public:
566 void IntCallback(int value) {
567 EXPECT_EQ(expected_thread_, Thread::Current());
568 int_value_ = value;
569 }
570 void AsyncInvokeIntCallback(GuardedAsyncInvoker* invoker, Thread* thread) {
571 expected_thread_ = thread;
572 invoker->AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
573 static_cast<GuardedAsyncInvokeTest*>(this));
574 invoke_started_.Set();
575 }
576 void SetExpectedThreadForIntCallback(Thread* thread) {
577 expected_thread_ = thread;
578 }
579
580 protected:
581 const static int kWaitTimeout = 1000;
582 GuardedAsyncInvokeTest()
583 : int_value_(0),
584 invoke_started_(true, false),
585 expected_thread_(nullptr) {}
586
587 int int_value_;
588 Event invoke_started_;
589 Thread* expected_thread_;
590};
591
592// Functor for creating an invoker.
593struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700594 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
595 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200596 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700597 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200598};
599
600// Test that we can call AsyncInvoke<void>() after the thread died.
601TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
602 // Create and start the thread.
jbauch555604a2016-04-26 03:13:22 -0700603 std::unique_ptr<Thread> thread(new Thread());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200604 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700605 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200606 // Create the invoker on |thread|.
607 thread->Invoke<void>(CreateInvoker(&invoker));
608 // Kill |thread|.
609 thread = nullptr;
610 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800611 AtomicBool called;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200612 EXPECT_FALSE(invoker->AsyncInvoke<void>(FunctorB(&called)));
613 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800614 WAIT(called.get(), kWaitTimeout);
615 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200616}
617
618// Test that we can call AsyncInvoke with callback after the thread died.
619TEST_F(GuardedAsyncInvokeTest, KillThreadWithCallback) {
620 // Create and start the thread.
jbauch555604a2016-04-26 03:13:22 -0700621 std::unique_ptr<Thread> thread(new Thread());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200622 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700623 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200624 // Create the invoker on |thread|.
625 thread->Invoke<void>(CreateInvoker(&invoker));
626 // Kill |thread|.
627 thread = nullptr;
628 // Try calling functor.
629 EXPECT_FALSE(
630 invoker->AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
631 static_cast<GuardedAsyncInvokeTest*>(this)));
632 // With thread gone, callback should be cancelled.
633 Thread::Current()->ProcessMessages(kWaitTimeout);
634 EXPECT_EQ(0, int_value_);
635}
636
637// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
638// when Thread is still alive.
639TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
640 GuardedAsyncInvoker invoker;
641 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800642 AtomicBool called;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200643 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800644 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200645}
646
647TEST_F(GuardedAsyncInvokeTest, WithCallback) {
648 GuardedAsyncInvoker invoker;
649 // Try calling functor.
650 SetExpectedThreadForIntCallback(Thread::Current());
651 EXPECT_TRUE(invoker.AsyncInvoke(FunctorA(),
652 &GuardedAsyncInvokeTest::IntCallback,
653 static_cast<GuardedAsyncInvokeTest*>(this)));
654 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
655}
656
657TEST_F(GuardedAsyncInvokeTest, CancelInvoker) {
658 // Try destroying invoker during call.
659 {
660 GuardedAsyncInvoker invoker;
661 EXPECT_TRUE(
662 invoker.AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
663 static_cast<GuardedAsyncInvokeTest*>(this)));
664 }
665 // With invoker gone, callback should be cancelled.
666 Thread::Current()->ProcessMessages(kWaitTimeout);
667 EXPECT_EQ(0, int_value_);
668}
669
670TEST_F(GuardedAsyncInvokeTest, CancelCallingThread) {
671 GuardedAsyncInvoker invoker;
672 // Try destroying calling thread during call.
673 {
674 Thread thread;
675 thread.Start();
676 // Try calling functor.
677 thread.Invoke<void>(Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
678 static_cast<GuardedAsyncInvokeTest*>(this),
679 &invoker, Thread::Current()));
680 // Wait for the call to begin.
681 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
682 }
683 // Calling thread is gone. Return message shouldn't happen.
684 Thread::Current()->ProcessMessages(kWaitTimeout);
685 EXPECT_EQ(0, int_value_);
686}
687
688TEST_F(GuardedAsyncInvokeTest, KillInvokerBeforeExecute) {
689 Thread thread;
690 thread.Start();
691 {
692 GuardedAsyncInvoker invoker;
693 // Try calling functor.
694 thread.Invoke<void>(Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
695 static_cast<GuardedAsyncInvokeTest*>(this),
696 &invoker, Thread::Current()));
697 // Wait for the call to begin.
698 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
699 }
700 // Invoker is destroyed. Function should not execute.
701 Thread::Current()->ProcessMessages(kWaitTimeout);
702 EXPECT_EQ(0, int_value_);
703}
704
705TEST_F(GuardedAsyncInvokeTest, Flush) {
706 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800707 AtomicBool flag1;
708 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200709 // Queue two async calls to the current thread.
710 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag1)));
711 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag2)));
712 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800713 EXPECT_FALSE(flag1.get());
714 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200715 // Force them to run now.
716 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800717 EXPECT_TRUE(flag1.get());
718 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200719}
720
721TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
722 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800723 AtomicBool flag1;
724 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200725 // Queue two async calls to the current thread, one with a message id.
726 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag1), 5));
727 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag2)));
728 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800729 EXPECT_FALSE(flag1.get());
730 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200731 // Execute pending calls with id == 5.
732 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800733 EXPECT_TRUE(flag1.get());
734 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200735 flag1 = false;
736 // Execute all pending calls. The id == 5 call should not execute again.
737 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800738 EXPECT_FALSE(flag1.get());
739 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200740}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000741
742#if defined(WEBRTC_WIN)
743class ComThreadTest : public testing::Test, public MessageHandler {
744 public:
745 ComThreadTest() : done_(false) {}
746 protected:
747 virtual void OnMessage(Message* message) {
748 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
749 // S_FALSE means the thread was already inited for a multithread apartment.
750 EXPECT_EQ(S_FALSE, hr);
751 if (SUCCEEDED(hr)) {
752 CoUninitialize();
753 }
754 done_ = true;
755 }
756 bool done_;
757};
758
759TEST_F(ComThreadTest, ComInited) {
760 Thread* thread = new ComThread();
761 EXPECT_TRUE(thread->Start());
762 thread->Post(this, 0);
763 EXPECT_TRUE_WAIT(done_, 1000);
764 delete thread;
765}
766#endif