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.
5 #include "base/synchronization/waitable_event.h"
9 #include "base/logging.h"
10 #include "base/numerics/safe_conversions.h"
11 #include "base/threading/thread_restrictions.h"
12 #include "base/time/time.h"
16 WaitableEvent::WaitableEvent(bool manual_reset
, bool signaled
)
17 : handle_(CreateEvent(NULL
, manual_reset
, signaled
, NULL
)) {
18 // We're probably going to crash anyways if this is ever NULL, so we might as
19 // well make our stack reports more informative by crashing here.
20 CHECK(handle_
.IsValid());
23 WaitableEvent::WaitableEvent(win::ScopedHandle handle
)
24 : handle_(handle
.Pass()) {
25 CHECK(handle_
.IsValid()) << "Tried to create WaitableEvent from NULL handle";
28 WaitableEvent::~WaitableEvent() {
31 void WaitableEvent::Reset() {
32 ResetEvent(handle_
.Get());
35 void WaitableEvent::Signal() {
36 SetEvent(handle_
.Get());
39 bool WaitableEvent::IsSignaled() {
40 return TimedWait(TimeDelta());
43 void WaitableEvent::Wait() {
44 base::ThreadRestrictions::AssertWaitAllowed();
45 DWORD result
= WaitForSingleObject(handle_
.Get(), INFINITE
);
46 // It is most unexpected that this should ever fail. Help consumers learn
47 // about it if it should ever fail.
48 DCHECK_EQ(WAIT_OBJECT_0
, result
) << "WaitForSingleObject failed";
51 bool WaitableEvent::TimedWait(const TimeDelta
& max_time
) {
52 base::ThreadRestrictions::AssertWaitAllowed();
53 DCHECK_GE(max_time
, TimeDelta());
54 // Truncate the timeout to milliseconds. The API specifies that this method
55 // can return in less than |max_time| (when returning false), as the argument
56 // is the maximum time that a caller is willing to wait.
57 DWORD timeout
= saturated_cast
<DWORD
>(max_time
.InMilliseconds());
59 DWORD result
= WaitForSingleObject(handle_
.Get(), timeout
);
66 // It is most unexpected that this should ever fail. Help consumers learn
67 // about it if it should ever fail.
68 NOTREACHED() << "WaitForSingleObject failed";
73 size_t WaitableEvent::WaitMany(WaitableEvent
** events
, size_t count
) {
74 base::ThreadRestrictions::AssertWaitAllowed();
75 HANDLE handles
[MAXIMUM_WAIT_OBJECTS
];
76 CHECK_LE(count
, static_cast<size_t>(MAXIMUM_WAIT_OBJECTS
))
77 << "Can only wait on " << MAXIMUM_WAIT_OBJECTS
<< " with WaitMany";
79 for (size_t i
= 0; i
< count
; ++i
)
80 handles
[i
] = events
[i
]->handle();
82 // The cast is safe because count is small - see the CHECK above.
84 WaitForMultipleObjects(static_cast<DWORD
>(count
),
86 FALSE
, // don't wait for all the objects
87 INFINITE
); // no timeout
88 if (result
>= WAIT_OBJECT_0
+ count
) {
89 DPLOG(FATAL
) << "WaitForMultipleObjects failed";
93 return result
- WAIT_OBJECT_0
;