2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
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.
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"
18 #include "webrtc/test/testsupport/gtest_disable.h"
20 #if defined(WEBRTC_WIN)
21 #include <comdef.h> // NOLINT
26 // Generates a sequence of numbers (collaboratively).
29 TestGenerator() : last(0), count(0) {}
32 int result = prev + last;
42 struct TestMessage : public MessageData {
43 explicit TestMessage(int v) : value(v) {}
44 virtual ~TestMessage() {}
49 // Receives on a socket and sends by posting messages.
50 class SocketClient : public TestGenerator, public sigslot::has_slots<> {
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);
64 SocketAddress address() const { return socket_->GetLocalAddress(); }
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);
73 post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
77 AsyncUDPSocket* socket_;
79 MessageHandler* post_handler_;
82 // Receives messages and sends on a socket.
83 class MessageClient : public MessageHandler, public TestGenerator {
85 MessageClient(Thread* pth, Socket* socket)
89 virtual ~MessageClient() {
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);
104 class CustomThread : public rtc::Thread {
107 virtual ~CustomThread() { Stop(); }
108 bool Start() { return false; }
111 return Thread::WrapCurrent();
113 void UnwrapCurrent() {
114 Thread::UnwrapCurrent();
119 // A thread that does nothing when it runs and signals an event
120 // when it is destroyed.
121 class SignalWhenDestroyedThread : public Thread {
123 SignalWhenDestroyedThread(Event* event)
127 virtual ~SignalWhenDestroyedThread() {
140 // Function objects to test Thread::Invoke.
142 int operator()() { return 42; }
146 explicit FunctorB(bool* flag) : flag_(flag) {}
147 void operator()() { if (flag_) *flag_ = true; }
153 Thread::Current()->ProcessMessages(50);
158 // See: https://code.google.com/p/webrtc/issues/detail?id=2409
159 TEST(ThreadTest, DISABLED_Main) {
160 const SocketAddress addr("127.0.0.1", 0);
162 // Create the messaging client on its own thread.
164 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
166 MessageClient msg_client(&th1, socket);
168 // Create the socket client on its own thread.
170 AsyncSocket* asocket =
171 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
172 SocketClient sock_client(asocket, addr, &th1, &msg_client);
174 socket->Connect(sock_client.address());
179 // Get the messages started.
180 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
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);
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).
190 th_main->ProcessMessages(200);
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);
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.
202 TEST(ThreadTest, Names) {
205 thread = new Thread();
206 EXPECT_TRUE(thread->Start());
209 thread = new Thread();
210 // Name with no object parameter
211 EXPECT_TRUE(thread->SetName("No object", NULL));
212 EXPECT_TRUE(thread->Start());
216 thread = new Thread();
217 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
218 EXPECT_TRUE(thread->Start());
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.
225 TEST(ThreadTest, Priorities) {
227 thread = new Thread();
228 EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
229 EXPECT_TRUE(thread->Start());
232 thread = new Thread();
233 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
234 EXPECT_TRUE(thread->Start());
238 thread = new Thread();
239 EXPECT_TRUE(thread->Start());
240 #if defined(WEBRTC_WIN)
241 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
243 EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
250 TEST(ThreadTest, Wrap) {
251 Thread* current_thread = Thread::Current();
252 current_thread->UnwrapCurrent();
253 CustomThread* cthread = new CustomThread();
254 EXPECT_TRUE(cthread->WrapCurrent());
255 EXPECT_TRUE(cthread->RunningForTest());
256 EXPECT_FALSE(cthread->IsOwned());
257 cthread->UnwrapCurrent();
258 EXPECT_FALSE(cthread->RunningForTest());
260 current_thread->WrapCurrent();
263 TEST(ThreadTest, Invoke) {
264 // Create and start the thread.
267 // Try calling functors.
268 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
270 FunctorB f2(&called);
271 thread.Invoke<void>(f2);
273 // Try calling bare functions.
275 static int Func1() { return 999; }
276 static void Func2() {}
278 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
279 thread.Invoke<void>(&LocalFuncs::Func2);
282 // Verifies that two threads calling Invoke on each other at the same time does
284 TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
286 Thread* current_thread = Thread::Current();
287 ASSERT_TRUE(current_thread != NULL);
290 other_thread.Start();
293 static void Set(bool* out) { *out = true; }
294 static void InvokeSet(Thread* thread, bool* out) {
295 thread->Invoke<void>(Bind(&Set, out));
300 other_thread.Invoke<void>(
301 Bind(&LocalFuncs::InvokeSet, current_thread, &called));
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
309 TEST(ThreadTest, ThreeThreadsInvoke) {
311 Thread* thread_a = Thread::Current();
312 Thread thread_b, thread_c;
318 explicit LockedBool(bool value) : value_(value) {}
320 void Set(bool value) {
321 CritScope lock(&crit_);
326 CritScope lock(&crit_);
331 CriticalSection crit_;
332 bool value_ GUARDED_BY(crit_);
336 static void Set(LockedBool* out) { out->Set(true); }
337 static void InvokeSet(Thread* thread, LockedBool* out) {
338 thread->Invoke<void>(Bind(&Set, out));
341 // Set |out| true and call InvokeSet on |thread|.
342 static void SetAndInvokeSet(LockedBool* out,
344 LockedBool* out_inner) {
346 InvokeSet(thread, out_inner);
349 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
350 // |thread1| starts the call.
351 static void AsyncInvokeSetAndWait(
352 Thread* thread1, Thread* thread2, LockedBool* out) {
353 CriticalSection crit;
354 LockedBool async_invoked(false);
356 AsyncInvoker invoker;
357 invoker.AsyncInvoke<void>(
358 thread1, Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
360 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
364 LockedBool thread_a_called(false);
366 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
367 // Thread B returns when C receives the call and C should be blocked until A
368 // starts to process messages.
369 thread_b.Invoke<void>(Bind(&LocalFuncs::AsyncInvokeSetAndWait,
370 &thread_c, thread_a, &thread_a_called));
371 EXPECT_FALSE(thread_a_called.Get());
373 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
376 class AsyncInvokeTest : public testing::Test {
378 void IntCallback(int value) {
379 EXPECT_EQ(expected_thread_, Thread::Current());
382 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
383 expected_thread_ = thread;
384 invoker->AsyncInvoke(thread, FunctorC(),
385 &AsyncInvokeTest::IntCallback,
386 static_cast<AsyncInvokeTest*>(this));
387 invoke_started_.Set();
389 void SetExpectedThreadForIntCallback(Thread* thread) {
390 expected_thread_ = thread;
394 enum { kWaitTimeout = 1000 };
397 invoke_started_(true, false),
398 expected_thread_(NULL) {}
401 Event invoke_started_;
402 Thread* expected_thread_;
405 TEST_F(AsyncInvokeTest, FireAndForget) {
406 AsyncInvoker invoker;
407 // Create and start the thread.
410 // Try calling functor.
412 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
413 EXPECT_TRUE_WAIT(called, kWaitTimeout);
416 TEST_F(AsyncInvokeTest, WithCallback) {
417 AsyncInvoker invoker;
418 // Create and start the thread.
421 // Try calling functor.
422 SetExpectedThreadForIntCallback(Thread::Current());
423 invoker.AsyncInvoke(&thread, FunctorA(),
424 &AsyncInvokeTest::IntCallback,
425 static_cast<AsyncInvokeTest*>(this));
426 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
429 TEST_F(AsyncInvokeTest, CancelInvoker) {
430 // Create and start the thread.
433 // Try destroying invoker during call.
435 AsyncInvoker invoker;
436 invoker.AsyncInvoke(&thread, FunctorC(),
437 &AsyncInvokeTest::IntCallback,
438 static_cast<AsyncInvokeTest*>(this));
440 // With invoker gone, callback should be cancelled.
441 Thread::Current()->ProcessMessages(kWaitTimeout);
442 EXPECT_EQ(0, int_value_);
445 TEST_F(AsyncInvokeTest, CancelCallingThread) {
446 AsyncInvoker invoker;
447 { // Create and start the thread.
450 // Try calling functor.
451 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
452 static_cast<AsyncInvokeTest*>(this),
453 &invoker, Thread::Current()));
454 // Wait for the call to begin.
455 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
457 // Calling thread is gone. Return message shouldn't happen.
458 Thread::Current()->ProcessMessages(kWaitTimeout);
459 EXPECT_EQ(0, int_value_);
462 TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
466 AsyncInvoker invoker;
467 // Try calling functor.
468 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
469 static_cast<AsyncInvokeTest*>(this),
470 &invoker, Thread::Current()));
471 // Wait for the call to begin.
472 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
474 // Invoker is destroyed. Function should not execute.
475 Thread::Current()->ProcessMessages(kWaitTimeout);
476 EXPECT_EQ(0, int_value_);
479 TEST_F(AsyncInvokeTest, Flush) {
480 AsyncInvoker invoker;
483 // Queue two async calls to the current thread.
484 invoker.AsyncInvoke<void>(Thread::Current(),
486 invoker.AsyncInvoke<void>(Thread::Current(),
488 // Because we haven't pumped messages, these should not have run yet.
491 // Force them to run now.
492 invoker.Flush(Thread::Current());
497 TEST_F(AsyncInvokeTest, FlushWithIds) {
498 AsyncInvoker invoker;
501 // Queue two async calls to the current thread, one with a message id.
502 invoker.AsyncInvoke<void>(Thread::Current(),
505 invoker.AsyncInvoke<void>(Thread::Current(),
507 // Because we haven't pumped messages, these should not have run yet.
510 // Execute pending calls with id == 5.
511 invoker.Flush(Thread::Current(), 5);
515 // Execute all pending calls. The id == 5 call should not execute again.
516 invoker.Flush(Thread::Current());
522 #if defined(WEBRTC_WIN)
523 class ComThreadTest : public testing::Test, public MessageHandler {
525 ComThreadTest() : done_(false) {}
527 virtual void OnMessage(Message* message) {
528 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
529 // S_FALSE means the thread was already inited for a multithread apartment.
530 EXPECT_EQ(S_FALSE, hr);
539 TEST_F(ComThreadTest, ComInited) {
540 Thread* thread = new ComThread();
541 EXPECT_TRUE(thread->Start());
542 thread->Post(this, 0);
543 EXPECT_TRUE_WAIT(done_, 1000);