3 * Copyright 2004--2011, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "talk/base/asyncinvoker.h"
29 #include "talk/base/asyncudpsocket.h"
30 #include "talk/base/event.h"
31 #include "talk/base/gunit.h"
32 #include "talk/base/physicalsocketserver.h"
33 #include "talk/base/socketaddress.h"
34 #include "talk/base/thread.h"
37 #include <comdef.h> // NOLINT
40 using namespace talk_base;
42 const int MAX = 65536;
44 // Generates a sequence of numbers (collaboratively).
47 TestGenerator() : last(0), count(0) {}
50 int result = prev + last;
60 struct TestMessage : public MessageData {
61 explicit TestMessage(int v) : value(v) {}
62 virtual ~TestMessage() {}
67 // Receives on a socket and sends by posting messages.
68 class SocketClient : public TestGenerator, public sigslot::has_slots<> {
70 SocketClient(AsyncSocket* socket, const SocketAddress& addr,
71 Thread* post_thread, MessageHandler* phandler)
72 : socket_(AsyncUDPSocket::Create(socket, addr)),
73 post_thread_(post_thread),
74 post_handler_(phandler) {
75 socket_->SignalReadPacket.connect(this, &SocketClient::OnPacket);
82 SocketAddress address() const { return socket_->GetLocalAddress(); }
84 void OnPacket(AsyncPacketSocket* socket, const char* buf, size_t size,
85 const SocketAddress& remote_addr,
86 const PacketTime& packet_time) {
87 EXPECT_EQ(size, sizeof(uint32));
88 uint32 prev = reinterpret_cast<const uint32*>(buf)[0];
89 uint32 result = Next(prev);
91 //socket_->set_readable(last < MAX);
92 post_thread_->PostDelayed(200, post_handler_, 0, new TestMessage(result));
96 AsyncUDPSocket* socket_;
98 MessageHandler* post_handler_;
101 // Receives messages and sends on a socket.
102 class MessageClient : public MessageHandler, public TestGenerator {
104 MessageClient(Thread* pth, Socket* socket)
105 : thread_(pth), socket_(socket) {
108 virtual ~MessageClient() {
112 virtual void OnMessage(Message *pmsg) {
113 TestMessage* msg = static_cast<TestMessage*>(pmsg->pdata);
114 int result = Next(msg->value);
115 EXPECT_GE(socket_->Send(&result, sizeof(result)), 0);
124 class CustomThread : public talk_base::Thread {
127 virtual ~CustomThread() { Stop(); }
128 bool Start() { return false; }
132 // A thread that does nothing when it runs and signals an event
133 // when it is destroyed.
134 class SignalWhenDestroyedThread : public Thread {
136 SignalWhenDestroyedThread(Event* event)
140 virtual ~SignalWhenDestroyedThread() {
153 // Function objects to test Thread::Invoke.
155 int operator()() { return 42; }
159 explicit FunctorB(bool* flag) : flag_(flag) {}
160 void operator()() { if (flag_) *flag_ = true; }
166 Thread::Current()->ProcessMessages(50);
171 // See: https://code.google.com/p/webrtc/issues/detail?id=2409
172 TEST(ThreadTest, DISABLED_Main) {
173 const SocketAddress addr("127.0.0.1", 0);
175 // Create the messaging client on its own thread.
177 Socket* socket = th1.socketserver()->CreateAsyncSocket(addr.family(),
179 MessageClient msg_client(&th1, socket);
181 // Create the socket client on its own thread.
183 AsyncSocket* asocket =
184 th2.socketserver()->CreateAsyncSocket(addr.family(), SOCK_DGRAM);
185 SocketClient sock_client(asocket, addr, &th1, &msg_client);
187 socket->Connect(sock_client.address());
192 // Get the messages started.
193 th1.PostDelayed(100, &msg_client, 0, new TestMessage(1));
195 // Give the clients a little while to run.
196 // Messages will be processed at 100, 300, 500, 700, 900.
197 Thread* th_main = Thread::Current();
198 th_main->ProcessMessages(1000);
200 // Stop the sending client. Give the receiver a bit longer to run, in case
201 // it is running on a machine that is under load (e.g. the build machine).
203 th_main->ProcessMessages(200);
206 // Make sure the results were correct
207 EXPECT_EQ(5, msg_client.count);
208 EXPECT_EQ(34, msg_client.last);
209 EXPECT_EQ(5, sock_client.count);
210 EXPECT_EQ(55, sock_client.last);
213 // Test that setting thread names doesn't cause a malfunction.
214 // There's no easy way to verify the name was set properly at this time.
215 TEST(ThreadTest, Names) {
218 thread = new Thread();
219 EXPECT_TRUE(thread->Start());
222 thread = new Thread();
223 // Name with no object parameter
224 EXPECT_TRUE(thread->SetName("No object", NULL));
225 EXPECT_TRUE(thread->Start());
229 thread = new Thread();
230 EXPECT_TRUE(thread->SetName("Abcdefghijklmnopqrstuvwxyz1234567890", this));
231 EXPECT_TRUE(thread->Start());
236 // Test that setting thread priorities doesn't cause a malfunction.
237 // There's no easy way to verify the priority was set properly at this time.
238 TEST(ThreadTest, Priorities) {
240 thread = new Thread();
241 EXPECT_TRUE(thread->SetPriority(PRIORITY_HIGH));
242 EXPECT_TRUE(thread->Start());
245 thread = new Thread();
246 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
247 EXPECT_TRUE(thread->Start());
251 thread = new Thread();
252 EXPECT_TRUE(thread->Start());
254 EXPECT_TRUE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
256 EXPECT_FALSE(thread->SetPriority(PRIORITY_ABOVE_NORMAL));
263 TEST(ThreadTest, Wrap) {
264 Thread* current_thread = Thread::Current();
265 current_thread->UnwrapCurrent();
266 CustomThread* cthread = new CustomThread();
267 EXPECT_TRUE(cthread->WrapCurrent());
268 EXPECT_TRUE(cthread->started());
269 EXPECT_FALSE(cthread->IsOwned());
270 cthread->UnwrapCurrent();
271 EXPECT_FALSE(cthread->started());
273 current_thread->WrapCurrent();
276 // Test that calling Release on a thread causes it to self-destruct when
277 // it's finished running
278 TEST(ThreadTest, Release) {
279 scoped_ptr<Event> event(new Event(true, false));
280 // Ensure the event is initialized.
283 Thread* thread = new SignalWhenDestroyedThread(event.get());
287 // The event should get signaled when the thread completes, which should
288 // be nearly instantaneous, since it doesn't do anything. For safety,
289 // give it 3 seconds in case the machine is under load.
290 bool signaled = event->Wait(3000);
291 EXPECT_TRUE(signaled);
294 TEST(ThreadTest, Invoke) {
295 // Create and start the thread.
298 // Try calling functors.
299 EXPECT_EQ(42, thread.Invoke<int>(FunctorA()));
301 FunctorB f2(&called);
302 thread.Invoke<void>(f2);
304 // Try calling bare functions.
306 static int Func1() { return 999; }
307 static void Func2() {}
309 EXPECT_EQ(999, thread.Invoke<int>(&LocalFuncs::Func1));
310 thread.Invoke<void>(&LocalFuncs::Func2);
313 class AsyncInvokeTest : public testing::Test {
315 void IntCallback(int value) {
316 EXPECT_EQ(expected_thread_, Thread::Current());
319 void AsyncInvokeIntCallback(AsyncInvoker* invoker, Thread* thread) {
320 expected_thread_ = thread;
321 invoker->AsyncInvoke(thread, FunctorC(),
322 &AsyncInvokeTest::IntCallback,
323 static_cast<AsyncInvokeTest*>(this));
324 invoke_started_.Set();
326 void SetExpectedThreadForIntCallback(Thread* thread) {
327 expected_thread_ = thread;
331 enum { kWaitTimeout = 1000 };
334 invoke_started_(true, false),
335 expected_thread_(NULL) {}
338 Event invoke_started_;
339 Thread* expected_thread_;
342 TEST_F(AsyncInvokeTest, FireAndForget) {
343 AsyncInvoker invoker;
344 // Create and start the thread.
347 // Try calling functor.
349 invoker.AsyncInvoke<void>(&thread, FunctorB(&called));
350 EXPECT_TRUE_WAIT(called, kWaitTimeout);
353 TEST_F(AsyncInvokeTest, WithCallback) {
354 AsyncInvoker invoker;
355 // Create and start the thread.
358 // Try calling functor.
359 SetExpectedThreadForIntCallback(Thread::Current());
360 invoker.AsyncInvoke(&thread, FunctorA(),
361 &AsyncInvokeTest::IntCallback,
362 static_cast<AsyncInvokeTest*>(this));
363 EXPECT_EQ_WAIT(42, int_value_, kWaitTimeout);
366 TEST_F(AsyncInvokeTest, CancelInvoker) {
367 // Create and start the thread.
370 // Try destroying invoker during call.
372 AsyncInvoker invoker;
373 invoker.AsyncInvoke(&thread, FunctorC(),
374 &AsyncInvokeTest::IntCallback,
375 static_cast<AsyncInvokeTest*>(this));
377 // With invoker gone, callback should be cancelled.
378 Thread::Current()->ProcessMessages(kWaitTimeout);
379 EXPECT_EQ(0, int_value_);
382 TEST_F(AsyncInvokeTest, CancelCallingThread) {
383 AsyncInvoker invoker;
384 { // Create and start the thread.
387 // Try calling functor.
388 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
389 static_cast<AsyncInvokeTest*>(this),
390 &invoker, Thread::Current()));
391 // Wait for the call to begin.
392 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
394 // Calling thread is gone. Return message shouldn't happen.
395 Thread::Current()->ProcessMessages(kWaitTimeout);
396 EXPECT_EQ(0, int_value_);
399 TEST_F(AsyncInvokeTest, KillInvokerBeforeExecute) {
403 AsyncInvoker invoker;
404 // Try calling functor.
405 thread.Invoke<void>(Bind(&AsyncInvokeTest::AsyncInvokeIntCallback,
406 static_cast<AsyncInvokeTest*>(this),
407 &invoker, Thread::Current()));
408 // Wait for the call to begin.
409 ASSERT_TRUE(invoke_started_.Wait(kWaitTimeout));
411 // Invoker is destroyed. Function should not execute.
412 Thread::Current()->ProcessMessages(kWaitTimeout);
413 EXPECT_EQ(0, int_value_);
416 TEST_F(AsyncInvokeTest, Flush) {
417 AsyncInvoker invoker;
420 // Queue two async calls to the current thread.
421 invoker.AsyncInvoke<void>(Thread::Current(),
423 invoker.AsyncInvoke<void>(Thread::Current(),
425 // Because we haven't pumped messages, these should not have run yet.
428 // Force them to run now.
429 invoker.Flush(Thread::Current());
434 TEST_F(AsyncInvokeTest, FlushWithIds) {
435 AsyncInvoker invoker;
438 // Queue two async calls to the current thread, one with a message id.
439 invoker.AsyncInvoke<void>(Thread::Current(),
442 invoker.AsyncInvoke<void>(Thread::Current(),
444 // Because we haven't pumped messages, these should not have run yet.
447 // Execute pending calls with id == 5.
448 invoker.Flush(Thread::Current(), 5);
452 // Execute all pending calls. The id == 5 call should not execute again.
453 invoker.Flush(Thread::Current());
460 class ComThreadTest : public testing::Test, public MessageHandler {
462 ComThreadTest() : done_(false) {}
464 virtual void OnMessage(Message* message) {
465 HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
466 // S_FALSE means the thread was already inited for a multithread apartment.
467 EXPECT_EQ(S_FALSE, hr);
476 TEST_F(ComThreadTest, ComInited) {
477 Thread* thread = new ComThread();
478 EXPECT_TRUE(thread->Start());
479 thread->Post(this, 0);
480 EXPECT_TRUE_WAIT(done_, 1000);