1 // Copyright (c) 2012 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.
5 #include "base/synchronization/waitable_event.h"
7 #include "base/compiler_specific.h"
8 #include "base/threading/platform_thread.h"
9 #include "base/time/time.h"
10 #include "testing/gtest/include/gtest/gtest.h"
14 TEST(WaitableEventTest
, ManualBasics
) {
15 WaitableEvent
event(true, false);
17 EXPECT_FALSE(event
.IsSignaled());
20 EXPECT_TRUE(event
.IsSignaled());
21 EXPECT_TRUE(event
.IsSignaled());
24 EXPECT_FALSE(event
.IsSignaled());
25 EXPECT_FALSE(event
.TimedWait(TimeDelta::FromMilliseconds(10)));
29 EXPECT_TRUE(event
.TimedWait(TimeDelta::FromMilliseconds(10)));
32 TEST(WaitableEventTest
, AutoBasics
) {
33 WaitableEvent
event(false, false);
35 EXPECT_FALSE(event
.IsSignaled());
38 EXPECT_TRUE(event
.IsSignaled());
39 EXPECT_FALSE(event
.IsSignaled());
42 EXPECT_FALSE(event
.IsSignaled());
43 EXPECT_FALSE(event
.TimedWait(TimeDelta::FromMilliseconds(10)));
47 EXPECT_FALSE(event
.TimedWait(TimeDelta::FromMilliseconds(10)));
50 EXPECT_TRUE(event
.TimedWait(TimeDelta::FromMilliseconds(10)));
53 TEST(WaitableEventTest
, WaitManyShortcut
) {
55 for (unsigned i
= 0; i
< 5; ++i
)
56 ev
[i
] = new WaitableEvent(false, false);
59 EXPECT_EQ(WaitableEvent::WaitMany(ev
, 5), 3u);
62 EXPECT_EQ(WaitableEvent::WaitMany(ev
, 5), 3u);
65 EXPECT_EQ(WaitableEvent::WaitMany(ev
, 5), 4u);
68 EXPECT_EQ(WaitableEvent::WaitMany(ev
, 5), 0u);
70 for (unsigned i
= 0; i
< 5; ++i
)
74 class WaitableEventSignaler
: public PlatformThread::Delegate
{
76 WaitableEventSignaler(double seconds
, WaitableEvent
* ev
)
81 virtual void ThreadMain() OVERRIDE
{
82 PlatformThread::Sleep(TimeDelta::FromSecondsD(seconds_
));
87 const double seconds_
;
88 WaitableEvent
*const ev_
;
91 TEST(WaitableEventTest
, WaitAndDelete
) {
92 // This test tests that if a WaitableEvent can be safely deleted
93 // when |Wait| is done without additional synchrnization.
94 // If this test crashes, it is a bug.
96 WaitableEvent
* ev
= new WaitableEvent(false, false);
98 WaitableEventSignaler
signaler(0.01, ev
);
99 PlatformThreadHandle thread
;
100 PlatformThread::Create(0, &signaler
, &thread
);
105 PlatformThread::Join(thread
);
108 TEST(WaitableEventTest
, WaitMany
) {
109 // This test tests that if a WaitableEvent can be safely deleted
110 // when |WaitMany| is done without additional synchrnization.
111 // If this test crashes, it is a bug.
113 WaitableEvent
* ev
[5];
114 for (unsigned i
= 0; i
< 5; ++i
)
115 ev
[i
] = new WaitableEvent(false, false);
117 WaitableEventSignaler
signaler(0.01, ev
[2]);
118 PlatformThreadHandle thread
;
119 PlatformThread::Create(0, &signaler
, &thread
);
121 size_t index
= WaitableEvent::WaitMany(ev
, 5);
123 for (unsigned i
= 0; i
< 5; ++i
)
126 PlatformThread::Join(thread
);
127 EXPECT_EQ(2u, index
);