blob: 41edd731d0993ac8853674b475a8b5c0cb4a3387 [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"
16#include "webrtc/base/socketaddress.h"
17#include "webrtc/base/thread.h"
henrike@webrtc.orgfded02c2014-09-19 13:10:10 +000018#include "webrtc/test/testsupport/gtest_disable.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019
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) {
69 EXPECT_EQ(size, sizeof(uint32));
70 uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
71 uint32 result = Next(prev);
72
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
140// Function objects to test Thread::Invoke.
141struct FunctorA {
142 int operator()() { return 42; }
143};
144class FunctorB {
145 public:
146 explicit FunctorB(bool* flag) : flag_(flag) {}
147 void operator()() { if (flag_) *flag_ = true; }
148 private:
149 bool* flag_;
150};
151struct FunctorC {
152 int operator()() {
153 Thread::Current()->ProcessMessages(50);
154 return 24;
155 }
156};
157
158// See: https://code.google.com/p/webrtc/issues/detail?id=2409
159TEST(ThreadTest, DISABLED_Main) {
160 const SocketAddress addr("127.0.0.1", 0);
161
162 // Create the messaging client on its own thread.
163 Thread th1;
164 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
165 SOCK_DGRAM);
166 MessageClient msg_client(&th1, socket);
167
168 // Create the socket client on its own thread.
169 Thread th2;
170 AsyncSocket* asocket =
171 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
172 SocketClient sock_client(asocket, addr, &th1, &msg_client);
173
174 socket->Connect(sock_client.address());
175
176 th1.Start();
177 th2.Start();
178
179 // Get the messages started.
180 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
181
182 // Give the clients a little while to run.
183 // Messages will be processed at 100, 300, 500, 700, 900.
184 Thread* th_main = Thread::Current();
185 th_main->ProcessMessages(1000);
186
187 // Stop the sending client. Give the receiver a bit longer to run, in case
188 // it is running on a machine that is under load (e.g. the build machine).
189 th1.Stop();
190 th_main->ProcessMessages(200);
191 th2.Stop();
192
193 // Make sure the results were correct
194 EXPECT_EQ(5, msg_client.count);
195 EXPECT_EQ(34, msg_client.last);
196 EXPECT_EQ(5, sock_client.count);
197 EXPECT_EQ(55, sock_client.last);
198}
199
200// Test that setting thread names doesn't cause a malfunction.
201// There's no easy way to verify the name was set properly at this time.
henrike@webrtc.orgfded02c2014-09-19 13:10:10 +0000202TEST(ThreadTest, DISABLED_ON_MAC(Names)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203 // Default name
204 Thread *thread;
205 thread = new Thread();
206 EXPECT_TRUE(thread->Start());
207 thread->Stop();
208 delete thread;
209 thread = new Thread();
210 // Name with no object parameter
211 EXPECT_TRUE(thread->SetName("No object", NULL));
212 EXPECT_TRUE(thread->Start());
213 thread->Stop();
214 delete thread;
215 // Really long name
216 thread = new Thread();
217 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
218 EXPECT_TRUE(thread->Start());
219 thread->Stop();
220 delete thread;
221}
222
223// Test that setting thread priorities doesn't cause a malfunction.
224// There's no easy way to verify the priority was set properly at this time.
henrike@webrtc.orgfded02c2014-09-19 13:10:10 +0000225TEST(ThreadTest, DISABLED_ON_MAC(Priorities)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 Thread *thread;
227 thread = new Thread();
228 EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
229 EXPECT_TRUE(thread->Start());
230 thread->Stop();
231 delete thread;
232 thread = new Thread();
233 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
234 EXPECT_TRUE(thread->Start());
235 thread->Stop();
236 delete thread;
237
238 thread = new Thread();
239 EXPECT_TRUE(thread->Start());
240#if defined(WEBRTC_WIN)
241 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
242#else
243 EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
244#endif
245 thread->Stop();
246 delete thread;
247
248}
249
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000250TEST(ThreadTest, Wrap) {
251 Thread* current_thread = Thread::Current();
252 current_thread->UnwrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 CustomThread* cthread = new CustomThread();
254 EXPECT_TRUE(cthread->WrapCurrent());
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000255 EXPECT_TRUE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 EXPECT_FALSE(cthread->IsOwned());
257 cthread->UnwrapCurrent();
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000258 EXPECT_FALSE(cthread->RunningForTest());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259 delete cthread;
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000260 current_thread->WrapCurrent();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261}
262
henrike@webrtc.orgfded02c2014-09-19 13:10:10 +0000263TEST(ThreadTest, DISABLED_ON_MAC(Invoke)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 // Create and start the thread.
265 Thread thread;
266 thread.Start();
267 // Try calling functors.
268 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
269 bool called = false;
270 FunctorB f2(&called);
271 thread.Invoke<void>(f2);
272 EXPECT_TRUE(called);
273 // Try calling bare functions.
274 struct LocalFuncs {
275 static int Func1() { return 999; }
276 static void Func2() {}
277 };
278 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
279 thread.Invoke<void>(&LocalFuncs::Func2);
280}
281
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000282// Verifies that two threads calling Invoke on each other at the same time does
283// not deadlock.
284TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
285 AutoThread thread;
286 Thread* current_thread = Thread::Current();
287 ASSERT_TRUE(current_thread != NULL);
288
289 Thread other_thread;
290 other_thread.Start();
291
292 struct LocalFuncs {
293 static void Set(bool* out) { *out = true; }
294 static void InvokeSet(Thread* thread, bool* out) {
295 thread->Invoke<void>(Bind(&Set, out));
296 }
297 };
298
299 bool called = false;
300 other_thread.Invoke<void>(
301 Bind(&LocalFuncs::InvokeSet, current_thread, &called));
302
303 EXPECT_TRUE(called);
304}
305
306// Verifies that if thread A invokes a call on thread B and thread C is trying
307// to invoke A at the same time, thread A does not handle C's invoke while
308// invoking B.
309TEST(ThreadTest, ThreeThreadsInvoke) {
310 AutoThread thread;
311 Thread* thread_a = Thread::Current();
312 Thread thread_b, thread_c;
313 thread_b.Start();
314 thread_c.Start();
315
316 struct LocalFuncs {
317 static void Set(bool* out) { *out = true; }
318 static void InvokeSet(Thread* thread, bool* out) {
319 thread->Invoke<void>(Bind(&Set, out));
320 }
321
322 // Set |out| true and call InvokeSet on |thread|.
323 static void SetAndInvokeSet(bool* out, Thread* thread, bool* out_inner) {
324 *out = true;
325 InvokeSet(thread, out_inner);
326 }
327
328 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
329 // |thread1| starts the call.
330 static void AsyncInvokeSetAndWait(
331 Thread* thread1, Thread* thread2, bool* out) {
332 bool async_invoked = false;
333
334 AsyncInvoker invoker;
335 invoker.AsyncInvoke<void>(
336 thread1, Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
337
338 EXPECT_TRUE_WAIT(async_invoked, 2000);
339 }
340 };
341
342 bool thread_a_called = false;
343
344 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
345 // Thread B returns when C receives the call and C should be blocked until A
346 // starts to process messages.
347 thread_b.Invoke<void>(Bind(&LocalFuncs::AsyncInvokeSetAndWait,
348 &thread_c, thread_a, &thread_a_called));
349 EXPECT_FALSE(thread_a_called);
350
351 EXPECT_TRUE_WAIT(thread_a_called, 2000);
352}
353
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354class AsyncInvokeTest : public testing::Test {
355 public:
356 void IntCallback(int value) {
357 EXPECT_EQ(expected_thread_, Thread::Current());
358 int_value_ = value;
359 }
360 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
361 expected_thread_ = thread;
362 invoker->AsyncInvoke(thread, FunctorC(),
363 &AsyncInvokeTest::IntCallback,
364 static_cast<AsyncInvokeTest*>(this));
365 invoke_started_.Set();
366 }
367 void SetExpectedThreadForIntCallback(Thread* thread) {
368 expected_thread_ = thread;
369 }
370
371 protected:
372 enum { kWaitTimeout = 1000 };
373 AsyncInvokeTest()
374 : int_value_(0),
375 invoke_started_(true, false),
376 expected_thread_(NULL) {}
377
378 int int_value_;
379 Event invoke_started_;
380 Thread* expected_thread_;
381};
382
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000383TEST_F(AsyncInvokeTest, FireAndForget) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384 AsyncInvoker invoker;
385 // Create and start the thread.
386 Thread thread;
387 thread.Start();
388 // Try calling functor.
389 bool called = false;
390 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
391 EXPECT_TRUE_WAIT(called, kWaitTimeout);
392}
393
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000394TEST_F(AsyncInvokeTest, DISABLED_WithCallback) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000395 AsyncInvoker invoker;
396 // Create and start the thread.
397 Thread thread;
398 thread.Start();
399 // Try calling functor.
400 SetExpectedThreadForIntCallback(Thread::Current());
401 invoker.AsyncInvoke(&thread, FunctorA(),
402 &AsyncInvokeTest::IntCallback,
403 static_cast<AsyncInvokeTest*>(this));
404 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
405}
406
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000407TEST_F(AsyncInvokeTest, DISABLED_CancelInvoker) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 // Create and start the thread.
409 Thread thread;
410 thread.Start();
411 // Try destroying invoker during call.
412 {
413 AsyncInvoker invoker;
414 invoker.AsyncInvoke(&thread, FunctorC(),
415 &AsyncInvokeTest::IntCallback,
416 static_cast<AsyncInvokeTest*>(this));
417 }
418 // With invoker gone, callback should be cancelled.
419 Thread::Current()->ProcessMessages(kWaitTimeout);
420 EXPECT_EQ(0, int_value_);
421}
422
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000423TEST_F(AsyncInvokeTest, DISABLED_CancelCallingThread) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424 AsyncInvoker invoker;
425 { // Create and start the thread.
426 Thread thread;
427 thread.Start();
428 // Try calling functor.
429 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
430 static_cast<AsyncInvokeTest*>(this),
431 &invoker, Thread::Current()));
432 // Wait for the call to begin.
433 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
434 }
435 // Calling thread is gone. Return message shouldn't happen.
436 Thread::Current()->ProcessMessages(kWaitTimeout);
437 EXPECT_EQ(0, int_value_);
438}
439
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000440TEST_F(AsyncInvokeTest, DISABLED_KillInvokerBeforeExecute) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000441 Thread thread;
442 thread.Start();
443 {
444 AsyncInvoker invoker;
445 // Try calling functor.
446 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
447 static_cast<AsyncInvokeTest*>(this),
448 &invoker, Thread::Current()));
449 // Wait for the call to begin.
450 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
451 }
452 // Invoker is destroyed. Function should not execute.
453 Thread::Current()->ProcessMessages(kWaitTimeout);
454 EXPECT_EQ(0, int_value_);
455}
456
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000457TEST_F(AsyncInvokeTest, DISABLED_Flush) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000458 AsyncInvoker invoker;
459 bool flag1 = false;
460 bool flag2 = false;
461 // Queue two async calls to the current thread.
462 invoker.AsyncInvoke<void>(Thread::Current(),
463 FunctorB(&flag1));
464 invoker.AsyncInvoke<void>(Thread::Current(),
465 FunctorB(&flag2));
466 // Because we haven't pumped messages, these should not have run yet.
467 EXPECT_FALSE(flag1);
468 EXPECT_FALSE(flag2);
469 // Force them to run now.
470 invoker.Flush(Thread::Current());
471 EXPECT_TRUE(flag1);
472 EXPECT_TRUE(flag2);
473}
474
kjellander@webrtc.org95705602014-09-19 14:49:37 +0000475TEST_F(AsyncInvokeTest, DISABLED_FlushWithIds) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000476 AsyncInvoker invoker;
477 bool flag1 = false;
478 bool flag2 = false;
479 // Queue two async calls to the current thread, one with a message id.
480 invoker.AsyncInvoke<void>(Thread::Current(),
481 FunctorB(&flag1),
482 5);
483 invoker.AsyncInvoke<void>(Thread::Current(),
484 FunctorB(&flag2));
485 // Because we haven't pumped messages, these should not have run yet.
486 EXPECT_FALSE(flag1);
487 EXPECT_FALSE(flag2);
488 // Execute pending calls with id == 5.
489 invoker.Flush(Thread::Current(), 5);
490 EXPECT_TRUE(flag1);
491 EXPECT_FALSE(flag2);
492 flag1 = false;
493 // Execute all pending calls. The id == 5 call should not execute again.
494 invoker.Flush(Thread::Current());
495 EXPECT_FALSE(flag1);
496 EXPECT_TRUE(flag2);
497}
498
499
500#if defined(WEBRTC_WIN)
501class ComThreadTest : public testing::Test, public MessageHandler {
502 public:
503 ComThreadTest() : done_(false) {}
504 protected:
505 virtual void OnMessage(Message* message) {
506 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
507 // S_FALSE means the thread was already inited for a multithread apartment.
508 EXPECT_EQ(S_FALSE, hr);
509 if (SUCCEEDED(hr)) {
510 CoUninitialize();
511 }
512 done_ = true;
513 }
514 bool done_;
515};
516
517TEST_F(ComThreadTest, ComInited) {
518 Thread* thread = new ComThread();
519 EXPECT_TRUE(thread->Start());
520 thread->Post(this, 0);
521 EXPECT_TRUE_WAIT(done_, 1000);
522 delete thread;
523}
524#endif