blob: 6afbf188d3269cf3a682cc3739ecba0bbfb97383 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// Copyright (c) 2006-2008 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.
darin@google.comc62bf352008-08-11 23:35:15 +09004
5#include "base/waitable_event.h"
6
7namespace base {
8
9WaitableEvent::WaitableEvent(bool manual_reset, bool signaled)
10 : lock_(),
11 cvar_(&lock_),
12 signaled_(signaled),
13 manual_reset_(manual_reset) {
14}
15
16WaitableEvent::~WaitableEvent() {
17 // Members are destroyed in the reverse of their initialization order, so we
18 // should not have to worry about lock_ being destroyed before cvar_.
19}
20
21void WaitableEvent::Reset() {
22 AutoLock locked(lock_);
23 signaled_ = false;
24}
25
26void WaitableEvent::Signal() {
27 AutoLock locked(lock_);
28 if (!signaled_) {
29 signaled_ = true;
30 if (manual_reset_) {
31 cvar_.Broadcast();
32 } else {
33 cvar_.Signal();
34 }
35 }
36}
37
38bool WaitableEvent::IsSignaled() {
39 return TimedWait(TimeDelta::FromMilliseconds(0));
40}
41
42bool WaitableEvent::Wait() {
43 AutoLock locked(lock_);
44 while (!signaled_)
45 cvar_.Wait();
46 if (!manual_reset_)
47 signaled_ = false;
48 return true;
49}
50
51bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
52 AutoLock locked(lock_);
53 // In case of spurious wake-ups, we need to adjust the amount of time that we
54 // spend sleeping.
55 TimeDelta total_time;
56 for (;;) {
57 TimeTicks start = TimeTicks::Now();
58 cvar_.TimedWait(max_time - total_time);
59 if (signaled_)
60 break;
61 total_time += TimeTicks::Now() - start;
62 if (total_time >= max_time)
63 break;
64 }
65 bool result = signaled_;
66 if (!manual_reset_)
67 signaled_ = false;
68 return result;
69}
70
71} // namespace base
license.botf003cfe2008-08-24 09:55:55 +090072