Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(326)

Side by Side Diff: webrtc/base/thread_unittest.cc

Issue 2877023002: Move webrtc/{base => rtc_base} (Closed)
Patch Set: update presubmit.py and DEPS include rules Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « webrtc/base/thread_darwin.mm ('k') | webrtc/base/timedelta.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /*
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 <memory>
12
13 #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"
18 #include "webrtc/base/sigslot.h"
19 #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
26 using namespace rtc;
27
28 // Generates a sequence of numbers (collaboratively).
29 class 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
44 struct 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.
52 class 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) {
71 EXPECT_EQ(size, sizeof(uint32_t));
72 uint32_t prev = reinterpret_cast<const uint32_t*>(buf)[0];
73 uint32_t result = Next(prev);
74
75 post_thread_->PostDelayed(RTC_FROM_HERE, 200, post_handler_, 0,
76 new TestMessage(result));
77 }
78
79 private:
80 AsyncUDPSocket* socket_;
81 Thread* post_thread_;
82 MessageHandler* post_handler_;
83 };
84
85 // Receives messages and sends on a socket.
86 class 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
107 class CustomThread : public rtc::Thread {
108 public:
109 CustomThread() {}
110 virtual ~CustomThread() { Stop(); }
111 bool Start() { return false; }
112
113 bool WrapCurrent() {
114 return Thread::WrapCurrent();
115 }
116 void UnwrapCurrent() {
117 Thread::UnwrapCurrent();
118 }
119 };
120
121
122 // A thread that does nothing when it runs and signals an event
123 // when it is destroyed.
124 class 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
143 // 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-s imple-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
157 class 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:
171 CriticalSection cs_;
172 bool flag_;
173 };
174
175 // Function objects to test Thread::Invoke.
176 struct FunctorA {
177 int operator()() { return 42; }
178 };
179 class FunctorB {
180 public:
181 explicit FunctorB(AtomicBool* flag) : flag_(flag) {}
182 void operator()() { if (flag_) *flag_ = true; }
183 private:
184 AtomicBool* flag_;
185 };
186 struct 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
194 TEST(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.
215 th1.PostDelayed(RTC_FROM_HERE, 100, &msg_client, 0, new TestMessage(1));
216
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.
237 TEST(ThreadTest, Names) {
238 // 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", nullptr));
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
258 TEST(ThreadTest, Wrap) {
259 Thread* current_thread = Thread::Current();
260 current_thread->UnwrapCurrent();
261 CustomThread* cthread = new CustomThread();
262 EXPECT_TRUE(cthread->WrapCurrent());
263 EXPECT_TRUE(cthread->RunningForTest());
264 EXPECT_FALSE(cthread->IsOwned());
265 cthread->UnwrapCurrent();
266 EXPECT_FALSE(cthread->RunningForTest());
267 delete cthread;
268 current_thread->WrapCurrent();
269 }
270
271 TEST(ThreadTest, Invoke) {
272 // Create and start the thread.
273 Thread thread;
274 thread.Start();
275 // Try calling functors.
276 EXPECT_EQ(42, thread.Invoke<int>(RTC_FROM_HERE, FunctorA()));
277 AtomicBool called;
278 FunctorB f2(&called);
279 thread.Invoke<void>(RTC_FROM_HERE, f2);
280 EXPECT_TRUE(called.get());
281 // Try calling bare functions.
282 struct LocalFuncs {
283 static int Func1() { return 999; }
284 static void Func2() {}
285 };
286 EXPECT_EQ(999, thread.Invoke<int>(RTC_FROM_HERE, &LocalFuncs::Func1));
287 thread.Invoke<void>(RTC_FROM_HERE, &LocalFuncs::Func2);
288 }
289
290 // Verifies that two threads calling Invoke on each other at the same time does
291 // not deadlock.
292 TEST(ThreadTest, TwoThreadsInvokeNoDeadlock) {
293 AutoThread thread;
294 Thread* current_thread = Thread::Current();
295 ASSERT_TRUE(current_thread != nullptr);
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) {
303 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
304 }
305 };
306
307 bool called = false;
308 other_thread.Invoke<void>(
309 RTC_FROM_HERE, Bind(&LocalFuncs::InvokeSet, current_thread, &called));
310
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.
317 TEST(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
324 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
343 struct LocalFuncs {
344 static void Set(LockedBool* out) { out->Set(true); }
345 static void InvokeSet(Thread* thread, LockedBool* out) {
346 thread->Invoke<void>(RTC_FROM_HERE, Bind(&Set, out));
347 }
348
349 // Set |out| true and call InvokeSet on |thread|.
350 static void SetAndInvokeSet(LockedBool* out,
351 Thread* thread,
352 LockedBool* out_inner) {
353 out->Set(true);
354 InvokeSet(thread, out_inner);
355 }
356
357 // Asynchronously invoke SetAndInvokeSet on |thread1| and wait until
358 // |thread1| starts the call.
359 static void AsyncInvokeSetAndWait(AsyncInvoker* invoker,
360 Thread* thread1,
361 Thread* thread2,
362 LockedBool* out) {
363 CriticalSection crit;
364 LockedBool async_invoked(false);
365
366 invoker->AsyncInvoke<void>(
367 RTC_FROM_HERE, thread1,
368 Bind(&SetAndInvokeSet, &async_invoked, thread2, out));
369
370 EXPECT_TRUE_WAIT(async_invoked.Get(), 2000);
371 }
372 };
373
374 AsyncInvoker invoker;
375 LockedBool thread_a_called(false);
376
377 // Start the sequence A --(invoke)--> B --(async invoke)--> C --(invoke)--> A.
378 // Thread B returns when C receives the call and C should be blocked until A
379 // starts to process messages.
380 thread_b.Invoke<void>(RTC_FROM_HERE,
381 Bind(&LocalFuncs::AsyncInvokeSetAndWait, &invoker,
382 &thread_c, thread_a, &thread_a_called));
383 EXPECT_FALSE(thread_a_called.Get());
384
385 EXPECT_TRUE_WAIT(thread_a_called.Get(), 2000);
386 }
387
388 // Set the name on a thread when the underlying QueueDestroyed signal is
389 // triggered. This causes an error if the object is already partially
390 // destroyed.
391 class SetNameOnSignalQueueDestroyedTester : public sigslot::has_slots<> {
392 public:
393 SetNameOnSignalQueueDestroyedTester(Thread* thread) : thread_(thread) {
394 thread->SignalQueueDestroyed.connect(
395 this, &SetNameOnSignalQueueDestroyedTester::OnQueueDestroyed);
396 }
397
398 void OnQueueDestroyed() {
399 // Makes sure that if we access the Thread while it's being destroyed, that
400 // it doesn't cause a problem because the vtable has been modified.
401 thread_->SetName("foo", nullptr);
402 }
403
404 private:
405 Thread* thread_;
406 };
407
408 TEST(ThreadTest, SetNameOnSignalQueueDestroyed) {
409 Thread* thread1 = new Thread();
410 SetNameOnSignalQueueDestroyedTester tester1(thread1);
411 delete thread1;
412
413 Thread* thread2 = new AutoThread();
414 SetNameOnSignalQueueDestroyedTester tester2(thread2);
415 delete thread2;
416 }
417
418 class AsyncInvokeTest : public testing::Test {
419 public:
420 void IntCallback(int value) {
421 EXPECT_EQ(expected_thread_, Thread::Current());
422 int_value_ = value;
423 }
424 void SetExpectedThreadForIntCallback(Thread* thread) {
425 expected_thread_ = thread;
426 }
427
428 protected:
429 enum { kWaitTimeout = 1000 };
430 AsyncInvokeTest()
431 : int_value_(0),
432 expected_thread_(nullptr) {}
433
434 int int_value_;
435 Thread* expected_thread_;
436 };
437
438 TEST_F(AsyncInvokeTest, FireAndForget) {
439 AsyncInvoker invoker;
440 // Create and start the thread.
441 Thread thread;
442 thread.Start();
443 // Try calling functor.
444 AtomicBool called;
445 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread, FunctorB(&called));
446 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
447 }
448
449 TEST_F(AsyncInvokeTest, KillInvokerDuringExecute) {
450 // Use these events to get in a state where the functor is in the middle of
451 // executing, and then to wait for it to finish, ensuring the "EXPECT_FALSE"
452 // is run.
453 Event functor_started(false, false);
454 Event functor_continue(false, false);
455 Event functor_finished(false, false);
456
457 Thread thread;
458 thread.Start();
459 volatile bool invoker_destroyed = false;
460 {
461 AsyncInvoker invoker;
462 invoker.AsyncInvoke<void>(RTC_FROM_HERE, &thread,
463 [&functor_started, &functor_continue,
464 &functor_finished, &invoker_destroyed] {
465 functor_started.Set();
466 functor_continue.Wait(Event::kForever);
467 rtc::Thread::Current()->SleepMs(kWaitTimeout);
468 EXPECT_FALSE(invoker_destroyed);
469 functor_finished.Set();
470 });
471 functor_started.Wait(Event::kForever);
472
473 // Allow the functor to continue and immediately destroy the invoker.
474 functor_continue.Set();
475 }
476
477 // If the destructor DIDN'T wait for the functor to finish executing, it will
478 // hit the EXPECT_FALSE(invoker_destroyed) after it finishes sleeping for a
479 // second.
480 invoker_destroyed = true;
481 functor_finished.Wait(Event::kForever);
482 }
483
484 TEST_F(AsyncInvokeTest, Flush) {
485 AsyncInvoker invoker;
486 AtomicBool flag1;
487 AtomicBool flag2;
488 // Queue two async calls to the current thread.
489 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1));
490 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
491 // Because we haven't pumped messages, these should not have run yet.
492 EXPECT_FALSE(flag1.get());
493 EXPECT_FALSE(flag2.get());
494 // Force them to run now.
495 invoker.Flush(Thread::Current());
496 EXPECT_TRUE(flag1.get());
497 EXPECT_TRUE(flag2.get());
498 }
499
500 TEST_F(AsyncInvokeTest, FlushWithIds) {
501 AsyncInvoker invoker;
502 AtomicBool flag1;
503 AtomicBool flag2;
504 // Queue two async calls to the current thread, one with a message id.
505 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag1),
506 5);
507 invoker.AsyncInvoke<void>(RTC_FROM_HERE, Thread::Current(), FunctorB(&flag2));
508 // Because we haven't pumped messages, these should not have run yet.
509 EXPECT_FALSE(flag1.get());
510 EXPECT_FALSE(flag2.get());
511 // Execute pending calls with id == 5.
512 invoker.Flush(Thread::Current(), 5);
513 EXPECT_TRUE(flag1.get());
514 EXPECT_FALSE(flag2.get());
515 flag1 = false;
516 // Execute all pending calls. The id == 5 call should not execute again.
517 invoker.Flush(Thread::Current());
518 EXPECT_FALSE(flag1.get());
519 EXPECT_TRUE(flag2.get());
520 }
521
522 class GuardedAsyncInvokeTest : public testing::Test {
523 public:
524 void IntCallback(int value) {
525 EXPECT_EQ(expected_thread_, Thread::Current());
526 int_value_ = value;
527 }
528 void SetExpectedThreadForIntCallback(Thread* thread) {
529 expected_thread_ = thread;
530 }
531
532 protected:
533 const static int kWaitTimeout = 1000;
534 GuardedAsyncInvokeTest()
535 : int_value_(0),
536 expected_thread_(nullptr) {}
537
538 int int_value_;
539 Thread* expected_thread_;
540 };
541
542 // Functor for creating an invoker.
543 struct CreateInvoker {
544 CreateInvoker(std::unique_ptr<GuardedAsyncInvoker>* invoker)
545 : invoker_(invoker) {}
546 void operator()() { invoker_->reset(new GuardedAsyncInvoker()); }
547 std::unique_ptr<GuardedAsyncInvoker>* invoker_;
548 };
549
550 // Test that we can call AsyncInvoke<void>() after the thread died.
551 TEST_F(GuardedAsyncInvokeTest, KillThreadFireAndForget) {
552 // Create and start the thread.
553 std::unique_ptr<Thread> thread(new Thread());
554 thread->Start();
555 std::unique_ptr<GuardedAsyncInvoker> invoker;
556 // Create the invoker on |thread|.
557 thread->Invoke<void>(RTC_FROM_HERE, CreateInvoker(&invoker));
558 // Kill |thread|.
559 thread = nullptr;
560 // Try calling functor.
561 AtomicBool called;
562 EXPECT_FALSE(invoker->AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
563 // With thread gone, nothing should happen.
564 WAIT(called.get(), kWaitTimeout);
565 EXPECT_FALSE(called.get());
566 }
567
568 // The remaining tests check that GuardedAsyncInvoker behaves as AsyncInvoker
569 // when Thread is still alive.
570 TEST_F(GuardedAsyncInvokeTest, FireAndForget) {
571 GuardedAsyncInvoker invoker;
572 // Try calling functor.
573 AtomicBool called;
574 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&called)));
575 EXPECT_TRUE_WAIT(called.get(), kWaitTimeout);
576 }
577
578 TEST_F(GuardedAsyncInvokeTest, Flush) {
579 GuardedAsyncInvoker invoker;
580 AtomicBool flag1;
581 AtomicBool flag2;
582 // Queue two async calls to the current thread.
583 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1)));
584 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
585 // Because we haven't pumped messages, these should not have run yet.
586 EXPECT_FALSE(flag1.get());
587 EXPECT_FALSE(flag2.get());
588 // Force them to run now.
589 EXPECT_TRUE(invoker.Flush());
590 EXPECT_TRUE(flag1.get());
591 EXPECT_TRUE(flag2.get());
592 }
593
594 TEST_F(GuardedAsyncInvokeTest, FlushWithIds) {
595 GuardedAsyncInvoker invoker;
596 AtomicBool flag1;
597 AtomicBool flag2;
598 // Queue two async calls to the current thread, one with a message id.
599 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag1), 5));
600 EXPECT_TRUE(invoker.AsyncInvoke<void>(RTC_FROM_HERE, FunctorB(&flag2)));
601 // Because we haven't pumped messages, these should not have run yet.
602 EXPECT_FALSE(flag1.get());
603 EXPECT_FALSE(flag2.get());
604 // Execute pending calls with id == 5.
605 EXPECT_TRUE(invoker.Flush(5));
606 EXPECT_TRUE(flag1.get());
607 EXPECT_FALSE(flag2.get());
608 flag1 = false;
609 // Execute all pending calls. The id == 5 call should not execute again.
610 EXPECT_TRUE(invoker.Flush());
611 EXPECT_FALSE(flag1.get());
612 EXPECT_TRUE(flag2.get());
613 }
OLDNEW
« no previous file with comments | « webrtc/base/thread_darwin.mm ('k') | webrtc/base/timedelta.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698