1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "base/time.h" 6 #include "base/synchronization/waitable_event.h" 7 #include "base/threading/platform_thread.h" 8 #include "testing/gtest/include/gtest/gtest.h" 9 10 namespace base { 11 12 TEST(WaitableEventTest, ManualBasics) { 13 WaitableEvent event(true, false); 14 15 EXPECT_FALSE(event.IsSignaled()); 16 17 event.Signal(); 18 EXPECT_TRUE(event.IsSignaled()); 19 EXPECT_TRUE(event.IsSignaled()); 20 21 event.Reset(); 22 EXPECT_FALSE(event.IsSignaled()); 23 EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10))); 24 25 event.Signal(); 26 EXPECT_TRUE(event.Wait()); 27 EXPECT_TRUE(event.TimedWait(TimeDelta::FromMilliseconds(10))); 28 } 29 30 TEST(WaitableEventTest, AutoBasics) { 31 WaitableEvent event(false, false); 32 33 EXPECT_FALSE(event.IsSignaled()); 34 35 event.Signal(); 36 EXPECT_TRUE(event.IsSignaled()); 37 EXPECT_FALSE(event.IsSignaled()); 38 39 event.Reset(); 40 EXPECT_FALSE(event.IsSignaled()); 41 EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10))); 42 43 event.Signal(); 44 EXPECT_TRUE(event.Wait()); 45 EXPECT_FALSE(event.TimedWait(TimeDelta::FromMilliseconds(10))); 46 47 event.Signal(); 48 EXPECT_TRUE(event.TimedWait(TimeDelta::FromMilliseconds(10))); 49 } 50 51 TEST(WaitableEventTest, WaitManyShortcut) { 52 WaitableEvent* ev[5]; 53 for (unsigned i = 0; i < 5; ++i) 54 ev[i] = new WaitableEvent(false, false); 55 56 ev[3]->Signal(); 57 EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 3u); 58 59 ev[3]->Signal(); 60 EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 3u); 61 62 ev[4]->Signal(); 63 EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 4u); 64 65 ev[0]->Signal(); 66 EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 0u); 67 68 for (unsigned i = 0; i < 5; ++i) 69 delete ev[i]; 70 } 71 72 class WaitableEventSignaler : public PlatformThread::Delegate { 73 public: 74 WaitableEventSignaler(double seconds, WaitableEvent* ev) 75 : seconds_(seconds), 76 ev_(ev) { 77 } 78 79 void ThreadMain() { 80 PlatformThread::Sleep(static_cast<int>(seconds_ * 1000)); 81 ev_->Signal(); 82 } 83 84 private: 85 const double seconds_; 86 WaitableEvent *const ev_; 87 }; 88 89 TEST(WaitableEventTest, WaitMany) { 90 WaitableEvent* ev[5]; 91 for (unsigned i = 0; i < 5; ++i) 92 ev[i] = new WaitableEvent(false, false); 93 94 WaitableEventSignaler signaler(0.1, ev[2]); 95 PlatformThreadHandle thread; 96 PlatformThread::Create(0, &signaler, &thread); 97 98 EXPECT_EQ(WaitableEvent::WaitMany(ev, 5), 2u); 99 100 PlatformThread::Join(thread); 101 102 for (unsigned i = 0; i < 5; ++i) 103 delete ev[i]; 104 } 105 106 } // namespace base 107