blob: b0c8cb59af952a3f7afea26702d758934987bdac [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
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070075 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
76 new TestMessage(result));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077 }
78
79 private:
80 AsyncUDPSocket* socket_;
81 Thread* post_thread_;
82 MessageHandler* post_handler_;
83};
84
85// Receives messages and sends on a socket.
86class MessageClient : public MessageHandler, public TestGenerator {
87 public:
88 MessageClient(Thread* pth, Socket* socket)
89 : socket_(socket) {
90 }
91
92 virtual ~MessageClient() {
93 delete socket_;
94 }
95
96 virtual void OnMessage(Message *pmsg) {
97 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
98 int result = Next(msg->value);
99 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
100 delete msg;
101 }
102
103 private:
104 Socket* socket_;
105};
106
107class CustomThread : public rtc::Thread {
108 public:
109 CustomThread() {}
110 virtual ~CustomThread() { Stop(); }
111 bool Start() { return false; }
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000112
113 bool WrapCurrent() {
114 return Thread::WrapCurrent();
115 }
116 void UnwrapCurrent() {
117 Thread::UnwrapCurrent();
118 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119};
120
121
122// A thread that does nothing when it runs and signals an event
123// when it is destroyed.
124class SignalWhenDestroyedThread : public Thread {
125 public:
126 SignalWhenDestroyedThread(Event* event)
127 : event_(event) {
128 }
129
130 virtual ~SignalWhenDestroyedThread() {
131 Stop();
132 event_->Set();
133 }
134
135 virtual void Run() {
136 // Do nothing.
137 }
138
139 private:
140 Event* event_;
141};
142
nissed9b75be2015-11-16 00:54:07 -0800143// A bool wrapped in a mutex, to avoid data races. Using a volatile
144// bool should be sufficient for correct code ("eventual consistency"
145// between caches is sufficient), but we can't tell the compiler about
146// that, and then tsan complains about a data race.
147
148// See also discussion at
149// http://stackoverflow.com/questions/7223164/is-mutex-needed-to-synchronize-a-simple-flag-between-pthreads
150
151// Using std::atomic<bool> or std::atomic_flag in C++11 is probably
152// the right thing to do, but those features are not yet allowed. Or
153// rtc::AtomicInt, if/when that is added. Since the use isn't
154// performance critical, use a plain critical section for the time
155// being.
156
157class AtomicBool {
158 public:
159 explicit AtomicBool(bool value = false) : flag_(value) {}
160 AtomicBool& operator=(bool value) {
161 CritScope scoped_lock(&cs_);
162 flag_ = value;
163 return *this;
164 }
165 bool get() const {
166 CritScope scoped_lock(&cs_);
167 return flag_;
168 }
169
170 private:
pbos5ad935c2016-01-25 03:52:44 -0800171 CriticalSection cs_;
nissed9b75be2015-11-16 00:54:07 -0800172 bool flag_;
173};
174
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175// Function objects to test Thread::Invoke.
176struct FunctorA {
177 int operator()() { return 42; }
178};
179class FunctorB {
180 public:
nissed9b75be2015-11-16 00:54:07 -0800181 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182 void operator()() { if (flag_) *flag_ = true; }
183 private:
nissed9b75be2015-11-16 00:54:07 -0800184 AtomicBool* flag_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185};
186struct FunctorC {
187 int operator()() {
188 Thread::Current()->ProcessMessages(50);
189 return 24;
190 }
191};
192
193// See: https://code.google.com/p/webrtc/issues/detail?id=2409
194TEST(ThreadTest, DISABLED_Main) {
195 const SocketAddress addr("127.0.0.1", 0);
196
197 // Create the messaging client on its own thread.
198 Thread th1;
199 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
200 SOCK_DGRAM);
201 MessageClient msg_client(&th1, socket);
202
203 // Create the socket client on its own thread.
204 Thread th2;
205 AsyncSocket* asocket =
206 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
207 SocketClient sock_client(asocket, addr, &th1, &msg_client);
208
209 socket->Connect(sock_client.address());
210
211 th1.Start();
212 th2.Start();
213
214 // Get the messages started.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700215 th1.PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216
217 // Give the clients a little while to run.
218 // Messages will be processed at 100, 300, 500, 700, 900.
219 Thread* th_main = Thread::Current();
220 th_main->ProcessMessages(1000);
221
222 // Stop the sending client. Give the receiver a bit longer to run, in case
223 // it is running on a machine that is under load (e.g. the build machine).
224 th1.Stop();
225 th_main->ProcessMessages(200);
226 th2.Stop();
227
228 // Make sure the results were correct
229 EXPECT_EQ(5, msg_client.count);
230 EXPECT_EQ(34, msg_client.last);
231 EXPECT_EQ(5, sock_client.count);
232 EXPECT_EQ(55, sock_client.last);
233}
234
235// Test that setting thread names doesn't cause a malfunction.
236// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000237TEST(ThreadTest, Names) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238 // Default name
239 Thread *thread;
240 thread = new Thread();
241 EXPECT_TRUE(thread->Start());
242 thread->Stop();
243 delete thread;
244 thread = new Thread();
245 // Name with no object parameter
246 EXPECT_TRUE(thread->SetName("No object", NULL));
247 EXPECT_TRUE(thread->Start());
248 thread->Stop();
249 delete thread;
250 // Really long name
251 thread = new Thread();
252 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
253 EXPECT_TRUE(thread->Start());
254 thread->Stop();
255 delete thread;
256}
257
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000258TEST(ThreadTest, Wrap) {
259 Thread* current_thread = Thread::Current();
260 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 CustomThread* cthread = new CustomThread();
262 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000263 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 EXPECT_FALSE(cthread->IsOwned());
265 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000266 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000268 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269}
270
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000271TEST(ThreadTest, Invoke) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272 // Create and start the thread.
273 Thread thread;
274 thread.Start();
275 // Try calling functors.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700276 EXPECT_EQ(42, thread.Invoke<int>(RTC_FROM_HERE, FunctorA()));
nissed9b75be2015-11-16 00:54:07 -0800277 AtomicBool called;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 FunctorB f2(&called);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700279 thread.Invoke<void>(RTC_FROM_HERE, f2);
nissed9b75be2015-11-16 00:54:07 -0800280 EXPECT_TRUE(called.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 // Try calling bare functions.
282 struct LocalFuncs {
283 static int Func1() { return 999; }
284 static void Func2() {}
285 };
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700286 EXPECT_EQ(999, thread.Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
287 thread.Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000288}
289
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000290// Verifies that two threads calling Invoke on each other at the same time does
291// not deadlock.
292TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
293 AutoThread thread;
294 Thread* current_thread = Thread::Current();
295 ASSERT_TRUE(current_thread != NULL);
296
297 Thread other_thread;
298 other_thread.Start();
299
300 struct LocalFuncs {
301 static void Set(bool* out) { *out = true; }
302 static void InvokeSet(Thread* thread, bool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700303 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000304 }
305 };
306
307 bool called = false;
308 other_thread.Invoke<void>(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700309 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000310
311 EXPECT_TRUE(called);
312}
313
314// Verifies that if thread A invokes a call on thread B and thread C is trying
315// to invoke A at the same time, thread A does not handle C's invoke while
316// invoking B.
317TEST(ThreadTest, ThreeThreadsInvoke) {
318 AutoThread thread;
319 Thread* thread_a = Thread::Current();
320 Thread thread_b, thread_c;
321 thread_b.Start();
322 thread_c.Start();
323
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000324 class LockedBool {
325 public:
326 explicit LockedBool(bool value) : value_(value) {}
327
328 void Set(bool value) {
329 CritScope lock(&crit_);
330 value_ = value;
331 }
332
333 bool Get() {
334 CritScope lock(&crit_);
335 return value_;
336 }
337
338 private:
339 CriticalSection crit_;
340 bool value_ GUARDED_BY(crit_);
341 };
342
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000343 struct LocalFuncs {
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000344 static void Set(LockedBool* out) { out->Set(true); }
345 static void InvokeSet(Thread* thread, LockedBool* out) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700346 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000347 }
348
349 // Set |out| true and call InvokeSet on |thread|.
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000350 static void SetAndInvokeSet(LockedBool* out,
351 Thread* thread,
352 LockedBool* out_inner) {
353 out->Set(true);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000354 InvokeSet(thread, out_inner);
355 }
356
357 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
358 // |thread1| starts the call.
359 static void AsyncInvokeSetAndWait(
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000360 Thread* thread1, Thread* thread2, LockedBool* out) {
361 CriticalSection crit;
362 LockedBool async_invoked(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000363
364 AsyncInvoker invoker;
365 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
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000373 LockedBool thread_a_called(false);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000374
375 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
376 // Thread B returns when C receives the call and C should be blocked until A
377 // starts to process messages.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700378 thread_b.Invoke<void>(RTC_FROM_HERE,
379 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &thread_c,
380 thread_a, &thread_a_called));
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000381 EXPECT_FALSE(thread_a_called.Get());
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000382
pbos@webrtc.orge93cbd12014-10-15 14:54:56 +0000383 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000384}
385
jbauch25d1f282016-02-05 00:25:02 -0800386// Set the name on a thread when the underlying QueueDestroyed signal is
387// triggered. This causes an error if the object is already partially
388// destroyed.
389class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
390 public:
391 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
392 thread->SignalQueueDestroyed.connect(
393 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
394 }
395
396 void OnQueueDestroyed() {
397 // Makes sure that if we access the Thread while it's being destroyed, that
398 // it doesn't cause a problem because the vtable has been modified.
399 thread_->SetName("foo", nullptr);
400 }
401
402 private:
403 Thread* thread_;
404};
405
406TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
407 Thread* thread1 = new Thread();
408 SetNameOnSignalQueueDestroyedTester tester1(thread1);
409 delete thread1;
410
411 Thread* thread2 = new AutoThread();
412 SetNameOnSignalQueueDestroyedTester tester2(thread2);
413 delete thread2;
414
415#if defined(WEBRTC_WIN)
416 Thread* thread3 = new ComThread();
417 SetNameOnSignalQueueDestroyedTester tester3(thread3);
418 delete thread3;
419#endif
420}
421
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422class AsyncInvokeTest : public testing::Test {
423 public:
424 void IntCallback(int value) {
425 EXPECT_EQ(expected_thread_, Thread::Current());
426 int_value_ = value;
427 }
428 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
429 expected_thread_ = thread;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700430 invoker->AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, thread, FunctorC(),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431 &AsyncInvokeTest::IntCallback,
432 static_cast<AsyncInvokeTest*>(this));
433 invoke_started_.Set();
434 }
435 void SetExpectedThreadForIntCallback(Thread* thread) {
436 expected_thread_ = thread;
437 }
438
439 protected:
440 enum { kWaitTimeout = 1000 };
441 AsyncInvokeTest()
442 : int_value_(0),
443 invoke_started_(true, false),
444 expected_thread_(NULL) {}
445
446 int int_value_;
447 Event invoke_started_;
448 Thread* expected_thread_;
449};
450
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000451TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000452 AsyncInvoker invoker;
453 // Create and start the thread.
454 Thread thread;
455 thread.Start();
456 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800457 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700458 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, FunctorB(&called));
nissed9b75be2015-11-16 00:54:07 -0800459 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000460}
461
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000462TEST_F(AsyncInvokeTest, WithCallback) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000463 AsyncInvoker invoker;
464 // Create and start the thread.
465 Thread thread;
466 thread.Start();
467 // Try calling functor.
468 SetExpectedThreadForIntCallback(Thread::Current());
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700469 invoker.AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, &thread, FunctorA(),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000470 &AsyncInvokeTest::IntCallback,
471 static_cast<AsyncInvokeTest*>(this));
472 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
473}
474
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000475TEST_F(AsyncInvokeTest, CancelInvoker) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000476 // Create and start the thread.
477 Thread thread;
478 thread.Start();
479 // Try destroying invoker during call.
480 {
481 AsyncInvoker invoker;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700482 invoker.AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, &thread, FunctorC(),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000483 &AsyncInvokeTest::IntCallback,
484 static_cast<AsyncInvokeTest*>(this));
485 }
486 // With invoker gone, callback should be cancelled.
487 Thread::Current()->ProcessMessages(kWaitTimeout);
488 EXPECT_EQ(0, int_value_);
489}
490
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000491TEST_F(AsyncInvokeTest, CancelCallingThread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492 AsyncInvoker invoker;
493 { // Create and start the thread.
494 Thread thread;
495 thread.Start();
496 // Try calling functor.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700497 thread.Invoke<void>(
498 RTC_FROM_HERE,
499 Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
500 static_cast<AsyncInvokeTest*>(this), &invoker, Thread::Current()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501 // Wait for the call to begin.
502 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
503 }
504 // Calling thread is gone. Return message shouldn't happen.
505 Thread::Current()->ProcessMessages(kWaitTimeout);
506 EXPECT_EQ(0, int_value_);
507}
508
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000509TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510 Thread thread;
511 thread.Start();
512 {
513 AsyncInvoker invoker;
514 // Try calling functor.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700515 thread.Invoke<void>(
516 RTC_FROM_HERE,
517 Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
518 static_cast<AsyncInvokeTest*>(this), &invoker, Thread::Current()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 // Wait for the call to begin.
520 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
521 }
522 // Invoker is destroyed. Function should not execute.
523 Thread::Current()->ProcessMessages(kWaitTimeout);
524 EXPECT_EQ(0, int_value_);
525}
526
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000527TEST_F(AsyncInvokeTest, Flush) {
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.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700532 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
533 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800535 EXPECT_FALSE(flag1.get());
536 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537 // Force them to run now.
538 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800539 EXPECT_TRUE(flag1.get());
540 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541}
542
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000543TEST_F(AsyncInvokeTest, FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544 AsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800545 AtomicBool flag1;
546 AtomicBool flag2;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700548 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549 5);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700550 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800552 EXPECT_FALSE(flag1.get());
553 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554 // Execute pending calls with id == 5.
555 invoker.Flush(Thread::Current(), 5);
nissed9b75be2015-11-16 00:54:07 -0800556 EXPECT_TRUE(flag1.get());
557 EXPECT_FALSE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000558 flag1 = false;
559 // Execute all pending calls. The id == 5 call should not execute again.
560 invoker.Flush(Thread::Current());
nissed9b75be2015-11-16 00:54:07 -0800561 EXPECT_FALSE(flag1.get());
562 EXPECT_TRUE(flag2.get());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563}
564
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200565class GuardedAsyncInvokeTest : public testing::Test {
566 public:
567 void IntCallback(int value) {
568 EXPECT_EQ(expected_thread_, Thread::Current());
569 int_value_ = value;
570 }
571 void AsyncInvokeIntCallback(GuardedAsyncInvoker* invoker, Thread* thread) {
572 expected_thread_ = thread;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700573 invoker->AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, FunctorC(),
574 &GuardedAsyncInvokeTest::IntCallback,
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200575 static_cast<GuardedAsyncInvokeTest*>(this));
576 invoke_started_.Set();
577 }
578 void SetExpectedThreadForIntCallback(Thread* thread) {
579 expected_thread_ = thread;
580 }
581
582 protected:
583 const static int kWaitTimeout = 1000;
584 GuardedAsyncInvokeTest()
585 : int_value_(0),
586 invoke_started_(true, false),
587 expected_thread_(nullptr) {}
588
589 int int_value_;
590 Event invoke_started_;
591 Thread* expected_thread_;
592};
593
594// Functor for creating an invoker.
595struct CreateInvoker {
jbauch555604a2016-04-26 03:13:22 -0700596 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
597 : invoker_(invoker) {}
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200598 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
jbauch555604a2016-04-26 03:13:22 -0700599 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200600};
601
602// Test that we can call AsyncInvoke<void>() after the thread died.
603TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
604 // Create and start the thread.
jbauch555604a2016-04-26 03:13:22 -0700605 std::unique_ptr<Thread> thread(new Thread());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200606 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700607 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200608 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700609 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200610 // Kill |thread|.
611 thread = nullptr;
612 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800613 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700614 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200615 // With thread gone, nothing should happen.
nissed9b75be2015-11-16 00:54:07 -0800616 WAIT(called.get(), kWaitTimeout);
617 EXPECT_FALSE(called.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200618}
619
620// Test that we can call AsyncInvoke with callback after the thread died.
621TEST_F(GuardedAsyncInvokeTest, KillThreadWithCallback) {
622 // Create and start the thread.
jbauch555604a2016-04-26 03:13:22 -0700623 std::unique_ptr<Thread> thread(new Thread());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200624 thread->Start();
jbauch555604a2016-04-26 03:13:22 -0700625 std::unique_ptr<GuardedAsyncInvoker> invoker;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200626 // Create the invoker on |thread|.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700627 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200628 // Kill |thread|.
629 thread = nullptr;
630 // Try calling functor.
631 EXPECT_FALSE(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700632 invoker->AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, FunctorC(),
633 &GuardedAsyncInvokeTest::IntCallback,
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200634 static_cast<GuardedAsyncInvokeTest*>(this)));
635 // With thread gone, callback should be cancelled.
636 Thread::Current()->ProcessMessages(kWaitTimeout);
637 EXPECT_EQ(0, int_value_);
638}
639
640// The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
641// when Thread is still alive.
642TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
643 GuardedAsyncInvoker invoker;
644 // Try calling functor.
nissed9b75be2015-11-16 00:54:07 -0800645 AtomicBool called;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700646 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
nissed9b75be2015-11-16 00:54:07 -0800647 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200648}
649
650TEST_F(GuardedAsyncInvokeTest, WithCallback) {
651 GuardedAsyncInvoker invoker;
652 // Try calling functor.
653 SetExpectedThreadForIntCallback(Thread::Current());
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700654 EXPECT_TRUE(invoker.AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, FunctorA(),
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200655 &GuardedAsyncInvokeTest::IntCallback,
656 static_cast<GuardedAsyncInvokeTest*>(this)));
657 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
658}
659
660TEST_F(GuardedAsyncInvokeTest, CancelInvoker) {
661 // Try destroying invoker during call.
662 {
663 GuardedAsyncInvoker invoker;
664 EXPECT_TRUE(
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700665 invoker.AsyncInvoke(RTC_FROM_HERE, RTC_FROM_HERE, FunctorC(),
666 &GuardedAsyncInvokeTest::IntCallback,
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200667 static_cast<GuardedAsyncInvokeTest*>(this)));
668 }
669 // With invoker gone, callback should be cancelled.
670 Thread::Current()->ProcessMessages(kWaitTimeout);
671 EXPECT_EQ(0, int_value_);
672}
673
674TEST_F(GuardedAsyncInvokeTest, CancelCallingThread) {
675 GuardedAsyncInvoker invoker;
676 // Try destroying calling thread during call.
677 {
678 Thread thread;
679 thread.Start();
680 // Try calling functor.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700681 thread.Invoke<void>(RTC_FROM_HERE,
682 Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200683 static_cast<GuardedAsyncInvokeTest*>(this),
684 &invoker, Thread::Current()));
685 // Wait for the call to begin.
686 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
687 }
688 // Calling thread is gone. Return message shouldn't happen.
689 Thread::Current()->ProcessMessages(kWaitTimeout);
690 EXPECT_EQ(0, int_value_);
691}
692
693TEST_F(GuardedAsyncInvokeTest, KillInvokerBeforeExecute) {
694 Thread thread;
695 thread.Start();
696 {
697 GuardedAsyncInvoker invoker;
698 // Try calling functor.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700699 thread.Invoke<void>(RTC_FROM_HERE,
700 Bind(&GuardedAsyncInvokeTest::AsyncInvokeIntCallback,
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200701 static_cast<GuardedAsyncInvokeTest*>(this),
702 &invoker, Thread::Current()));
703 // Wait for the call to begin.
704 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
705 }
706 // Invoker is destroyed. Function should not execute.
707 Thread::Current()->ProcessMessages(kWaitTimeout);
708 EXPECT_EQ(0, int_value_);
709}
710
711TEST_F(GuardedAsyncInvokeTest, Flush) {
712 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800713 AtomicBool flag1;
714 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200715 // Queue two async calls to the current thread.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700716 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
717 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200718 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800719 EXPECT_FALSE(flag1.get());
720 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200721 // Force them to run now.
722 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800723 EXPECT_TRUE(flag1.get());
724 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200725}
726
727TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
728 GuardedAsyncInvoker invoker;
nissed9b75be2015-11-16 00:54:07 -0800729 AtomicBool flag1;
730 AtomicBool flag2;
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200731 // Queue two async calls to the current thread, one with a message id.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700732 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
733 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200734 // Because we haven't pumped messages, these should not have run yet.
nissed9b75be2015-11-16 00:54:07 -0800735 EXPECT_FALSE(flag1.get());
736 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200737 // Execute pending calls with id == 5.
738 EXPECT_TRUE(invoker.Flush(5));
nissed9b75be2015-11-16 00:54:07 -0800739 EXPECT_TRUE(flag1.get());
740 EXPECT_FALSE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200741 flag1 = false;
742 // Execute all pending calls. The id == 5 call should not execute again.
743 EXPECT_TRUE(invoker.Flush());
nissed9b75be2015-11-16 00:54:07 -0800744 EXPECT_FALSE(flag1.get());
745 EXPECT_TRUE(flag2.get());
Magnus Jedverta1f590f2015-08-20 16:42:42 +0200746}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000747
748#if defined(WEBRTC_WIN)
749class ComThreadTest : public testing::Test, public MessageHandler {
750 public:
751 ComThreadTest() : done_(false) {}
752 protected:
753 virtual void OnMessage(Message* message) {
754 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
755 // S_FALSE means the thread was already inited for a multithread apartment.
756 EXPECT_EQ(S_FALSE, hr);
757 if (SUCCEEDED(hr)) {
758 CoUninitialize();
759 }
760 done_ = true;
761 }
762 bool done_;
763};
764
765TEST_F(ComThreadTest, ComInited) {
766 Thread* thread = new ComThread();
767 EXPECT_TRUE(thread->Start());
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700768 thread->Post(RTC_FROM_HERE, this, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000769 EXPECT_TRUE_WAIT(done_, 1000);
770 delete thread;
771}
772#endif