blob: 7889e29da8d2cd2c83fbe6f394f1a79b704e258c [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
11#include "webrtc/base/asyncinvoker.h"
12#include "webrtc/base/asyncudpsocket.h"
13#include "webrtc/base/event.h"
14#include "webrtc/base/gunit.h"
15#include "webrtc/base/physicalsocketserver.h"
jbauch25d1f282016-02-05 00:25:02 -080016#include "webrtc/base/sigslot.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017#include "webrtc/base/socketaddress.h"
18#include "webrtc/base/thread.h"
19
20#if defined(WEBRTC_WIN)
21#include <comdef.h> // NOLINT
22#endif
23
24using namespace rtc;
25
26// Generates a sequence of numbers (collaboratively).
27class TestGenerator {
28 public:
29 TestGenerator() : last(0), count(0) {}
30
31 int Next(int prev) {
32 int result = prev + last;
33 last = result;
34 count += 1;
35 return result;
36 }
37
38 int last;
39 int count;
40};
41
42struct TestMessage : public MessageData {
43 explicit TestMessage(int v) : value(v) {}
44 virtual ~TestMessage() {}
45
46 int value;
47};
48
49// Receives on a socket and sends by posting messages.
50class SocketClient : public TestGenerator, public sigslot::has_slots<> {
51 public:
52 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
53 Thread* post_thread, MessageHandler* phandler)
54 : socket_(AsyncUDPSocket::Create(socket, addr)),
55 post_thread_(post_thread),
56 post_handler_(phandler) {
57 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
58 }
59
60 ~SocketClient() {
61 delete socket_;
62 }
63
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
73 post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
74 }
75
76 private:
77 AsyncUDPSocket* socket_;
78 Thread* post_thread_;
79 MessageHandler* post_handler_;
80};
81
82// Receives messages and sends on a socket.
83class MessageClient : public MessageHandler, public TestGenerator {
84 public:
85 MessageClient(Thread* pth, Socket* socket)
86 : socket_(socket) {
87 }
88
89 virtual ~MessageClient() {
90 delete socket_;
91 }
92
93 virtual void OnMessage(Message *pmsg) {
94 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
95 int result = Next(msg->value);
96 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
97 delete msg;
98 }
99
100 private:
101 Socket* socket_;
102};
103
104class CustomThread : public rtc::Thread {
105 public:
106 CustomThread() {}
107 virtual ~CustomThread() { Stop(); }
108 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)
124 : event_(event) {
125 }
126
127 virtual ~SignalWhenDestroyedThread() {
128 Stop();
129 event_->Set();
130 }
131
132 virtual void Run() {
133 // 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
150// rtc::AtomicInt, if/when that is added. Since the use isn't
151// 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.
195 Thread th1;
196 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
197 SOCK_DGRAM);
198 MessageClient msg_client(&th1, socket);
199
200 // Create the socket client on its own thread.
201 Thread th2;
202 AsyncSocket* asocket =
203 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
204 SocketClient sock_client(asocket, addr, &th1, &msg_client);
205
206 socket->Connect(sock_client.address());
207
208 th1.Start();
209 th2.Start();
210
211 // Get the messages started.
212 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
213
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).
221 th1.Stop();
222 th_main->ProcessMessages(200);
223 th2.Stop();
224
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
236 Thread *thread;
237 thread = new Thread();
238 EXPECT_TRUE(thread->Start());
239 thread->Stop();
240 delete thread;
241 thread = new Thread();
242 // Name with no object parameter
243 EXPECT_TRUE(thread->SetName("No object", NULL));
244 EXPECT_TRUE(thread->Start());
245 thread->Stop();
246 delete thread;
247 // Really long name
248 thread = new Thread();
249 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
250 EXPECT_TRUE(thread->Start());
251 thread->Stop();
252 delete thread;
253}
254
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000255TEST(ThreadTest, Wrap) {
256 Thread* current_thread = Thread::Current();
257 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 CustomThread* cthread = new CustomThread();
259 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000260 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 EXPECT_FALSE(cthread->IsOwned());
262 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000263 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000265 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266}
267
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000268TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269 // Create and start the thread.
270 Thread thread;
271 thread.Start();
272 // Try calling functors.
273 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800274 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 FunctorB f2(&called);
276 thread.Invoke<void>(f2);
nissed9b75be2015-11-16 00:54:07 -0800277 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 // Try calling bare functions.
279 struct LocalFuncs {
280 static int Func1() { return 999; }
281 static void Func2() {}
282 };
283 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
284 thread.Invoke<void>(&LocalFuncs::Func2);
285}
286
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000287// Verifies that two threads calling Invoke on each other at the same time does
288// not deadlock.
289TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
290 AutoThread thread;
291 Thread* current_thread = Thread::Current();
292 ASSERT_TRUE(current_thread != NULL);
293
294 Thread other_thread;
295 other_thread.Start();
296
297 struct LocalFuncs {
298 static void Set(bool* out) { *out = true; }
299 static void InvokeSet(Thread* thread, bool* out) {
300 thread->Invoke<void>(Bind(&Set, out));
301 }
302 };
303
304 bool called = false;
305 other_thread.Invoke<void>(
306 Bind(&LocalFuncs::InvokeSet, current_thread, &called));
307
308 EXPECT_TRUE(called);
309}
310
311// Verifies that if thread A invokes a call on thread B and thread C is trying
312// to invoke A at the same time, thread A does not handle C's invoke while
313// invoking B.
314TEST(ThreadTest, ThreeThreadsInvoke) {
315 AutoThread thread;
316 Thread* thread_a = Thread::Current();
317 Thread thread_b, thread_c;
318 thread_b.Start();
319 thread_c.Start();
320
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000321 class LockedBool {
322 public:
323 explicit LockedBool(bool value) : value_(value) {}
324
325 void Set(bool value) {
326 CritScope lock(&crit_);
327 value_ = value;
328 }
329
330 bool Get() {
331 CritScope lock(&crit_);
332 return value_;
333 }
334
335 private:
336 CriticalSection crit_;
337 bool value_ GUARDED_BY(crit_);
338 };
339
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000340 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000341 static void Set(LockedBool* out) { out->Set(true); }
342 static void InvokeSet(Thread* thread, LockedBool* out) {
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000343 thread->Invoke<void>(Bind(&Set, out));
344 }
345
346 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000347 static void SetAndInvokeSet(LockedBool* out,
348 Thread* thread,
349 LockedBool* out_inner) {
350 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000351 InvokeSet(thread, out_inner);
352 }
353
354 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
355 // |thread1| starts the call.
356 static void AsyncInvokeSetAndWait(
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000357 Thread* thread1, Thread* thread2, LockedBool* out) {
358 CriticalSection crit;
359 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000360
361 AsyncInvoker invoker;
362 invoker.AsyncInvoke<void>(
363 thread1, Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
364
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000365 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000366 }
367 };
368
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.
374 thread_b.Invoke<void>(Bind(&LocalFuncs::AsyncInvokeSetAndWait,
375 &thread_c, thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000376 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000377
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000378 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000379}
380
jbauch25d1f282016-02-05 00:25:02 -0800381// Set the name on a thread when the underlying QueueDestroyed signal is
382// triggered. This causes an error if the object is already partially
383// destroyed.
384class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
385 public:
386 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
387 thread->SignalQueueDestroyed.connect(
388 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
389 }
390
391 void OnQueueDestroyed() {
392 // Makes sure that if we access the Thread while it's being destroyed, that
393 // it doesn't cause a problem because the vtable has been modified.
394 thread_->SetName("foo", nullptr);
395 }
396
397 private:
398 Thread* thread_;
399};
400
401TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
402 Thread* thread1 = new Thread();
403 SetNameOnSignalQueueDestroyedTester tester1(thread1);
404 delete thread1;
405
406 Thread* thread2 = new AutoThread();
407 SetNameOnSignalQueueDestroyedTester tester2(thread2);
408 delete thread2;
409
410#if defined(WEBRTC_WIN)
411 Thread* thread3 = new ComThread();
412 SetNameOnSignalQueueDestroyedTester tester3(thread3);
413 delete thread3;
414#endif
415}
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 }
423 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
424 expected_thread_ = thread;
425 invoker->AsyncInvoke(thread, FunctorC(),
426 &AsyncInvokeTest::IntCallback,
427 static_cast<AsyncInvokeTest*>(this));
428 invoke_started_.Set();
429 }
430 void SetExpectedThreadForIntCallback(Thread* thread) {
431 expected_thread_ = thread;
432 }
433
434 protected:
435 enum { kWaitTimeout = 1000 };
436 AsyncInvokeTest()
437 : int_value_(0),
438 invoke_started_(true, false),
439 expected_thread_(NULL) {}
440
441 int int_value_;
442 Event invoke_started_;
443 Thread* expected_thread_;
444};
445
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000446TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447 AsyncInvoker invoker;
448 // Create and start the thread.
449 Thread thread;
450 thread.Start();
451 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800452 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000453 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800454 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455}
456
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000457TEST_F(AsyncInvokeTest, WithCallback) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000458 AsyncInvoker invoker;
459 // Create and start the thread.
460 Thread thread;
461 thread.Start();
462 // Try calling functor.
463 SetExpectedThreadForIntCallback(Thread::Current());
464 invoker.AsyncInvoke(&thread, FunctorA(),
465 &AsyncInvokeTest::IntCallback,
466 static_cast<AsyncInvokeTest*>(this));
467 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
468}
469
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000470TEST_F(AsyncInvokeTest, CancelInvoker) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000471 // Create and start the thread.
472 Thread thread;
473 thread.Start();
474 // Try destroying invoker during call.
475 {
476 AsyncInvoker invoker;
477 invoker.AsyncInvoke(&thread, FunctorC(),
478 &AsyncInvokeTest::IntCallback,
479 static_cast<AsyncInvokeTest*>(this));
480 }
481 // With invoker gone, callback should be cancelled.
482 Thread::Current()->ProcessMessages(kWaitTimeout);
483 EXPECT_EQ(0, int_value_);
484}
485
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000486TEST_F(AsyncInvokeTest, CancelCallingThread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000487 AsyncInvoker invoker;
488 { // Create and start the thread.
489 Thread thread;
490 thread.Start();
491 // Try calling functor.
492 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
493 static_cast<AsyncInvokeTest*>(this),
494 &invoker, Thread::Current()));
495 // Wait for the call to begin.
496 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
497 }
498 // Calling thread is gone. Return message shouldn't happen.
499 Thread::Current()->ProcessMessages(kWaitTimeout);
500 EXPECT_EQ(0, int_value_);
501}
502
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000503TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504 Thread thread;
505 thread.Start();
506 {
507 AsyncInvoker invoker;
508 // Try calling functor.
509 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
510 static_cast<AsyncInvokeTest*>(this),
511 &invoker, Thread::Current()));
512 // Wait for the call to begin.
513 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
514 }
515 // Invoker is destroyed. Function should not execute.
516 Thread::Current()->ProcessMessages(kWaitTimeout);
517 EXPECT_EQ(0, int_value_);
518}
519
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000520TEST_F(AsyncInvokeTest, Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800522 AtomicBool flag1;
523 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 // Queue two async calls to the current thread.
525 invoker.AsyncInvoke<void>(Thread::Current(),
526 FunctorB(&flag1));
527 invoker.AsyncInvoke<void>(Thread::Current(),
528 FunctorB(&flag2));
529 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800530 EXPECT_FALSE(flag1.get());
531 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532 // Force them to run now.
533 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800534 EXPECT_TRUE(flag1.get());
535 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536}
537
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000538TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800540 AtomicBool flag1;
541 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542 // Queue two async calls to the current thread, one with a message id.
543 invoker.AsyncInvoke<void>(Thread::Current(),
544 FunctorB(&flag1),
545 5);
546 invoker.AsyncInvoke<void>(Thread::Current(),
547 FunctorB(&flag2));
548 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800549 EXPECT_FALSE(flag1.get());
550 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551 // Execute pending calls with id == 5.
552 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800553 EXPECT_TRUE(flag1.get());
554 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555 flag1 = false;
556 // Execute all pending calls. The id == 5 call should not execute again.
557 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800558 EXPECT_FALSE(flag1.get());
559 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000560}
561
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200562class GuardedAsyncInvokeTest : public testing::Test {
563 public:
564 void IntCallback(int value) {
565 EXPECT_EQ(expected_thread_, Thread::Current());
566 int_value_ = value;
567 }
568 void AsyncInvokeIntCallback(GuardedAsyncInvoker* invoker, Thread* thread) {
569 expected_thread_ = thread;
570 invoker->AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
571 static_cast<GuardedAsyncInvokeTest*>(this));
572 invoke_started_.Set();
573 }
574 void SetExpectedThreadForIntCallback(Thread* thread) {
575 expected_thread_ = thread;
576 }
577
578 protected:
579 const static int kWaitTimeout = 1000;
580 GuardedAsyncInvokeTest()
581 : int_value_(0),
582 invoke_started_(true, false),
583 expected_thread_(nullptr) {}
584
585 int int_value_;
586 Event invoke_started_;
587 Thread* expected_thread_;
588};
589
590// Functor for creating an invoker.
591struct CreateInvoker {
592 CreateInvoker(scoped_ptr<GuardedAsyncInvoker>* invoker) : invoker_(invoker) {}
593 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
594 scoped_ptr<GuardedAsyncInvoker>* invoker_;
595};
596
597// Test that we can call AsyncInvoke<void>() after the thread died.
598TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
599 // Create and start the thread.
600 scoped_ptr<Thread> thread(new Thread());
601 thread->Start();
602 scoped_ptr<GuardedAsyncInvoker> invoker;
603 // Create the invoker on |thread|.
604 thread->Invoke<void>(CreateInvoker(&invoker));
605 // Kill |thread|.
606 thread = nullptr;
607 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800608 AtomicBool called;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200609 EXPECT_FALSE(invoker->AsyncInvoke<void>(FunctorB(&called)));
610 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800611 WAIT(called.get(), kWaitTimeout);
612 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200613}
614
615// Test that we can call AsyncInvoke with callback after the thread died.
616TEST_F(GuardedAsyncInvokeTest, KillThreadWithCallback) {
617 // Create and start the thread.
618 scoped_ptr<Thread> thread(new Thread());
619 thread->Start();
620 scoped_ptr<GuardedAsyncInvoker> invoker;
621 // Create the invoker on |thread|.
622 thread->Invoke<void>(CreateInvoker(&invoker));
623 // Kill |thread|.
624 thread = nullptr;
625 // Try calling functor.
626 EXPECT_FALSE(
627 invoker->AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
628 static_cast<GuardedAsyncInvokeTest*>(this)));
629 // With thread gone, callback should be cancelled.
630 Thread::Current()->ProcessMessages(kWaitTimeout);
631 EXPECT_EQ(0, int_value_);
632}
633
634// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
635// when Thread is still alive.
636TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
637 GuardedAsyncInvoker invoker;
638 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800639 AtomicBool called;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200640 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800641 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200642}
643
644TEST_F(GuardedAsyncInvokeTest, WithCallback) {
645 GuardedAsyncInvoker invoker;
646 // Try calling functor.
647 SetExpectedThreadForIntCallback(Thread::Current());
648 EXPECT_TRUE(invoker.AsyncInvoke(FunctorA(),
649 &GuardedAsyncInvokeTest::IntCallback,
650 static_cast<GuardedAsyncInvokeTest*>(this)));
651 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
652}
653
654TEST_F(GuardedAsyncInvokeTest, CancelInvoker) {
655 // Try destroying invoker during call.
656 {
657 GuardedAsyncInvoker invoker;
658 EXPECT_TRUE(
659 invoker.AsyncInvoke(FunctorC(), &GuardedAsyncInvokeTest::IntCallback,
660 static_cast<GuardedAsyncInvokeTest*>(this)));
661 }
662 // With invoker gone, callback should be cancelled.
663 Thread::Current()->ProcessMessages(kWaitTimeout);
664 EXPECT_EQ(0, int_value_);
665}
666
667TEST_F(GuardedAsyncInvokeTest, CancelCallingThread) {
668 GuardedAsyncInvoker invoker;
669 // Try destroying calling thread during call.
670 {
671 Thread thread;
672 thread.Start();
673 // Try calling functor.
674 thread.Invoke<void>(Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
675 static_cast<GuardedAsyncInvokeTest*>(this),
676 &invoker, Thread::Current()));
677 // Wait for the call to begin.
678 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
679 }
680 // Calling thread is gone. Return message shouldn't happen.
681 Thread::Current()->ProcessMessages(kWaitTimeout);
682 EXPECT_EQ(0, int_value_);
683}
684
685TEST_F(GuardedAsyncInvokeTest, KillInvokerBeforeExecute) {
686 Thread thread;
687 thread.Start();
688 {
689 GuardedAsyncInvoker invoker;
690 // Try calling functor.
691 thread.Invoke<void>(Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
692 static_cast<GuardedAsyncInvokeTest*>(this),
693 &invoker, Thread::Current()));
694 // Wait for the call to begin.
695 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
696 }
697 // Invoker is destroyed. Function should not execute.
698 Thread::Current()->ProcessMessages(kWaitTimeout);
699 EXPECT_EQ(0, int_value_);
700}
701
702TEST_F(GuardedAsyncInvokeTest, Flush) {
703 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800704 AtomicBool flag1;
705 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200706 // Queue two async calls to the current thread.
707 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag1)));
708 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag2)));
709 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800710 EXPECT_FALSE(flag1.get());
711 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200712 // Force them to run now.
713 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800714 EXPECT_TRUE(flag1.get());
715 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200716}
717
718TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
719 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800720 AtomicBool flag1;
721 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200722 // Queue two async calls to the current thread, one with a message id.
723 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag1), 5));
724 EXPECT_TRUE(invoker.AsyncInvoke<void>(FunctorB(&flag2)));
725 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800726 EXPECT_FALSE(flag1.get());
727 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200728 // Execute pending calls with id == 5.
729 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800730 EXPECT_TRUE(flag1.get());
731 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200732 flag1 = false;
733 // Execute all pending calls. The id == 5 call should not execute again.
734 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800735 EXPECT_FALSE(flag1.get());
736 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200737}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000738
739#if defined(WEBRTC_WIN)
740class ComThreadTest : public testing::Test, public MessageHandler {
741 public:
742 ComThreadTest() : done_(false) {}
743 protected:
744 virtual void OnMessage(Message* message) {
745 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
746 // S_FALSE means the thread was already inited for a multithread apartment.
747 EXPECT_EQ(S_FALSE, hr);
748 if (SUCCEEDED(hr)) {
749 CoUninitialize();
750 }
751 done_ = true;
752 }
753 bool done_;
754};
755
756TEST_F(ComThreadTest, ComInited) {
757 Thread* thread = new ComThread();
758 EXPECT_TRUE(thread->Start());
759 thread->Post(this, 0);
760 EXPECT_TRUE_WAIT(done_, 1000);
761 delete thread;
762}
763#endif