1 : // 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.
4 :
5 : #include "base/waitable_event.h"
6 :
7 : #include "base/condition_variable.h"
8 : #include "base/lock.h"
9 : #include "base/message_loop.h"
10 :
11 : // -----------------------------------------------------------------------------
12 : // A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
13 : // support cross-process events (where one process can signal an event which
14 : // others are waiting on). Because of this, we can avoid having one thread per
15 : // listener in several cases.
16 : //
17 : // The WaitableEvent maintains a list of waiters, protected by a lock. Each
18 : // waiter is either an async wait, in which case we have a Task and the
19 : // MessageLoop to run it on, or a blocking wait, in which case we have the
20 : // condition variable to signal.
21 : //
22 : // Waiting involves grabbing the lock and adding oneself to the wait list. Async
23 : // waits can be canceled, which means grabbing the lock and removing oneself
24 : // from the list.
25 : //
26 : // Waiting on multiple events is handled by adding a single, synchronous wait to
27 : // the wait-list of many events. An event passes a pointer to itself when
28 : // firing a waiter and so we can store that pointer to find out which event
29 : // triggered.
30 : // -----------------------------------------------------------------------------
31 :
32 : namespace base {
33 :
34 : // -----------------------------------------------------------------------------
35 : // This is just an abstract base class for waking the two types of waiters
36 : // -----------------------------------------------------------------------------
37 4305 : WaitableEvent::WaitableEvent(bool manual_reset, bool initially_signaled)
38 4305 : : kernel_(new WaitableEventKernel(manual_reset, initially_signaled)) {
39 4305 : }
40 :
41 2839 : WaitableEvent::~WaitableEvent() {
42 2839 : }
43 :
44 0 : void WaitableEvent::Reset() {
45 0 : AutoLock locked(kernel_->lock_);
46 0 : kernel_->signaled_ = false;
47 0 : }
48 :
49 1420 : void WaitableEvent::Signal() {
50 2840 : AutoLock locked(kernel_->lock_);
51 :
52 1420 : if (kernel_->signaled_)
53 : return;
54 :
55 1420 : if (kernel_->manual_reset_) {
56 0 : SignalAll();
57 0 : kernel_->signaled_ = true;
58 : } else {
59 : // In the case of auto reset, if no waiters were woken, we remain
60 : // signaled.
61 1420 : if (!SignalOne())
62 2 : kernel_->signaled_ = true;
63 : }
64 : }
65 :
66 0 : bool WaitableEvent::IsSignaled() {
67 0 : AutoLock locked(kernel_->lock_);
68 :
69 0 : const bool result = kernel_->signaled_;
70 0 : if (result && !kernel_->manual_reset_)
71 0 : kernel_->signaled_ = false;
72 0 : return result;
73 : }
74 :
75 : // -----------------------------------------------------------------------------
76 : // Synchronous waits
77 :
78 : // -----------------------------------------------------------------------------
79 : // This is an synchronous waiter. The thread is waiting on the given condition
80 : // variable and the fired flag in this object.
81 : // -----------------------------------------------------------------------------
82 : class SyncWaiter : public WaitableEvent::Waiter {
83 : public:
84 1418 : SyncWaiter(ConditionVariable* cv, Lock* lock)
85 : : fired_(false),
86 : cv_(cv),
87 : lock_(lock),
88 1418 : signaling_event_(NULL) {
89 1418 : }
90 :
91 1418 : bool Fire(WaitableEvent *signaling_event) {
92 1418 : lock_->Acquire();
93 1418 : const bool previous_value = fired_;
94 1418 : fired_ = true;
95 1418 : if (!previous_value)
96 1418 : signaling_event_ = signaling_event;
97 1418 : lock_->Release();
98 :
99 1418 : if (previous_value)
100 0 : return false;
101 :
102 1418 : cv_->Broadcast();
103 :
104 : // SyncWaiters are stack allocated on the stack of the blocking thread.
105 1418 : return true;
106 : }
107 :
108 0 : WaitableEvent* signaled_event() const {
109 0 : return signaling_event_;
110 : }
111 :
112 : // ---------------------------------------------------------------------------
113 : // These waiters are always stack allocated and don't delete themselves. Thus
114 : // there's no problem and the ABA tag is the same as the object pointer.
115 : // ---------------------------------------------------------------------------
116 0 : bool Compare(void* tag) {
117 0 : return this == tag;
118 : }
119 :
120 : // ---------------------------------------------------------------------------
121 : // Called with lock held.
122 : // ---------------------------------------------------------------------------
123 4254 : bool fired() const {
124 4254 : return fired_;
125 : }
126 :
127 : // ---------------------------------------------------------------------------
128 : // During a TimedWait, we need a way to make sure that an auto-reset
129 : // WaitableEvent doesn't think that this event has been signaled between
130 : // unlocking it and removing it from the wait-list. Called with lock held.
131 : // ---------------------------------------------------------------------------
132 1418 : void Disable() {
133 1418 : fired_ = true;
134 1418 : }
135 :
136 : private:
137 : bool fired_;
138 : ConditionVariable *const cv_;
139 : Lock *const lock_;
140 : WaitableEvent* signaling_event_; // The WaitableEvent which woke us
141 : };
142 :
143 1420 : bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
144 1420 : const Time end_time(Time::Now() + max_time);
145 1420 : const bool finite_time = max_time.ToInternalValue() >= 0;
146 :
147 1420 : kernel_->lock_.Acquire();
148 1420 : if (kernel_->signaled_) {
149 2 : if (!kernel_->manual_reset_) {
150 : // In this case we were signaled when we had no waiters. Now that
151 : // someone has waited upon us, we can automatically reset.
152 2 : kernel_->signaled_ = false;
153 : }
154 :
155 2 : kernel_->lock_.Release();
156 2 : return true;
157 : }
158 :
159 2836 : Lock lock;
160 1418 : lock.Acquire();
161 2836 : ConditionVariable cv(&lock);
162 1418 : SyncWaiter sw(&cv, &lock);
163 :
164 1418 : Enqueue(&sw);
165 1418 : kernel_->lock_.Release();
166 : // We are violating locking order here by holding the SyncWaiter lock but not
167 : // the WaitableEvent lock. However, this is safe because we don't lock @lock_
168 : // again before unlocking it.
169 :
170 1418 : for (;;) {
171 2836 : const Time current_time(Time::Now());
172 :
173 2836 : if (sw.fired() || (finite_time && current_time >= end_time)) {
174 1418 : const bool return_value = sw.fired();
175 :
176 : // We can't acquire @lock_ before releasing @lock (because of locking
177 : // order), however, inbetween the two a signal could be fired and @sw
178 : // would accept it, however we will still return false, so the signal
179 : // would be lost on an auto-reset WaitableEvent. Thus we call Disable
180 : // which makes sw::Fire return false.
181 1418 : sw.Disable();
182 1418 : lock.Release();
183 :
184 1418 : kernel_->lock_.Acquire();
185 1418 : kernel_->Dequeue(&sw, &sw);
186 1418 : kernel_->lock_.Release();
187 :
188 1418 : return return_value;
189 : }
190 :
191 1418 : if (finite_time) {
192 0 : const TimeDelta max_wait(end_time - current_time);
193 0 : cv.TimedWait(max_wait);
194 : } else {
195 1418 : cv.Wait();
196 : }
197 : }
198 : }
199 :
200 1420 : bool WaitableEvent::Wait() {
201 1420 : return TimedWait(TimeDelta::FromSeconds(-1));
202 : }
203 :
204 : // -----------------------------------------------------------------------------
205 :
206 :
207 : // -----------------------------------------------------------------------------
208 : // Synchronous waiting on multiple objects.
209 :
210 : static bool // StrictWeakOrdering
211 0 : cmp_fst_addr(const std::pair<WaitableEvent*, unsigned> &a,
212 : const std::pair<WaitableEvent*, unsigned> &b) {
213 0 : return a.first < b.first;
214 : }
215 :
216 : // static
217 0 : size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables,
218 : size_t count) {
219 0 : DCHECK(count) << "Cannot wait on no events";
220 :
221 : // We need to acquire the locks in a globally consistent order. Thus we sort
222 : // the array of waitables by address. We actually sort a pairs so that we can
223 : // map back to the original index values later.
224 0 : std::vector<std::pair<WaitableEvent*, size_t> > waitables;
225 0 : waitables.reserve(count);
226 0 : for (size_t i = 0; i < count; ++i)
227 0 : waitables.push_back(std::make_pair(raw_waitables[i], i));
228 :
229 0 : DCHECK_EQ(count, waitables.size());
230 :
231 0 : sort(waitables.begin(), waitables.end(), cmp_fst_addr);
232 :
233 : // The set of waitables must be distinct. Since we have just sorted by
234 : // address, we can check this cheaply by comparing pairs of consecutive
235 : // elements.
236 0 : for (size_t i = 0; i < waitables.size() - 1; ++i) {
237 0 : DCHECK(waitables[i].first != waitables[i+1].first);
238 : }
239 :
240 0 : Lock lock;
241 0 : ConditionVariable cv(&lock);
242 0 : SyncWaiter sw(&cv, &lock);
243 :
244 0 : const size_t r = EnqueueMany(&waitables[0], count, &sw);
245 0 : if (r) {
246 : // One of the events is already signaled. The SyncWaiter has not been
247 : // enqueued anywhere. EnqueueMany returns the count of remaining waitables
248 : // when the signaled one was seen, so the index of the signaled event is
249 : // @count - @r.
250 0 : return waitables[count - r].second;
251 : }
252 :
253 : // At this point, we hold the locks on all the WaitableEvents and we have
254 : // enqueued our waiter in them all.
255 0 : lock.Acquire();
256 : // Release the WaitableEvent locks in the reverse order
257 0 : for (size_t i = 0; i < count; ++i) {
258 0 : waitables[count - (1 + i)].first->kernel_->lock_.Release();
259 : }
260 :
261 0 : for (;;) {
262 0 : if (sw.fired())
263 : break;
264 :
265 0 : cv.Wait();
266 : }
267 0 : lock.Release();
268 :
269 : // The address of the WaitableEvent which fired is stored in the SyncWaiter.
270 0 : WaitableEvent *const signaled_event = sw.signaled_event();
271 : // This will store the index of the raw_waitables which fired.
272 0 : size_t signaled_index = 0;
273 :
274 : // Take the locks of each WaitableEvent in turn (except the signaled one) and
275 : // remove our SyncWaiter from the wait-list
276 0 : for (size_t i = 0; i < count; ++i) {
277 0 : if (raw_waitables[i] != signaled_event) {
278 0 : raw_waitables[i]->kernel_->lock_.Acquire();
279 : // There's no possible ABA issue with the address of the SyncWaiter here
280 : // because it lives on the stack. Thus the tag value is just the pointer
281 : // value again.
282 0 : raw_waitables[i]->kernel_->Dequeue(&sw, &sw);
283 0 : raw_waitables[i]->kernel_->lock_.Release();
284 : } else {
285 0 : signaled_index = i;
286 : }
287 : }
288 :
289 0 : return signaled_index;
290 : }
291 :
292 : // -----------------------------------------------------------------------------
293 : // If return value == 0:
294 : // The locks of the WaitableEvents have been taken in order and the Waiter has
295 : // been enqueued in the wait-list of each. None of the WaitableEvents are
296 : // currently signaled
297 : // else:
298 : // None of the WaitableEvent locks are held. The Waiter has not been enqueued
299 : // in any of them and the return value is the index of the first WaitableEvent
300 : // which was signaled, from the end of the array.
301 : // -----------------------------------------------------------------------------
302 : // static
303 0 : size_t WaitableEvent::EnqueueMany
304 : (std::pair<WaitableEvent*, size_t>* waitables,
305 : size_t count, Waiter* waiter) {
306 0 : if (!count)
307 0 : return 0;
308 :
309 0 : waitables[0].first->kernel_->lock_.Acquire();
310 0 : if (waitables[0].first->kernel_->signaled_) {
311 0 : if (!waitables[0].first->kernel_->manual_reset_)
312 0 : waitables[0].first->kernel_->signaled_ = false;
313 0 : waitables[0].first->kernel_->lock_.Release();
314 0 : return count;
315 : }
316 :
317 0 : const size_t r = EnqueueMany(waitables + 1, count - 1, waiter);
318 0 : if (r) {
319 0 : waitables[0].first->kernel_->lock_.Release();
320 : } else {
321 0 : waitables[0].first->Enqueue(waiter);
322 : }
323 :
324 0 : return r;
325 : }
326 :
327 : // -----------------------------------------------------------------------------
328 :
329 :
330 : // -----------------------------------------------------------------------------
331 : // Private functions...
332 :
333 : // -----------------------------------------------------------------------------
334 : // Wake all waiting waiters. Called with lock held.
335 : // -----------------------------------------------------------------------------
336 0 : bool WaitableEvent::SignalAll() {
337 0 : bool signaled_at_least_one = false;
338 :
339 0 : for (std::list<Waiter*>::iterator
340 0 : i = kernel_->waiters_.begin(); i != kernel_->waiters_.end(); ++i) {
341 0 : if ((*i)->Fire(this))
342 0 : signaled_at_least_one = true;
343 : }
344 :
345 0 : kernel_->waiters_.clear();
346 0 : return signaled_at_least_one;
347 : }
348 :
349 : // ---------------------------------------------------------------------------
350 : // Try to wake a single waiter. Return true if one was woken. Called with lock
351 : // held.
352 : // ---------------------------------------------------------------------------
353 1420 : bool WaitableEvent::SignalOne() {
354 0 : for (;;) {
355 1420 : if (kernel_->waiters_.empty())
356 2 : return false;
357 :
358 1418 : const bool r = (*kernel_->waiters_.begin())->Fire(this);
359 1418 : kernel_->waiters_.pop_front();
360 1418 : if (r)
361 1418 : return true;
362 : }
363 : }
364 :
365 : // -----------------------------------------------------------------------------
366 : // Add a waiter to the list of those waiting. Called with lock held.
367 : // -----------------------------------------------------------------------------
368 1418 : void WaitableEvent::Enqueue(Waiter* waiter) {
369 1418 : kernel_->waiters_.push_back(waiter);
370 1418 : }
371 :
372 : // -----------------------------------------------------------------------------
373 : // Remove a waiter from the list of those waiting. Return true if the waiter was
374 : // actually removed. Called with lock held.
375 : // -----------------------------------------------------------------------------
376 1418 : bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) {
377 2836 : for (std::list<Waiter*>::iterator
378 2836 : i = waiters_.begin(); i != waiters_.end(); ++i) {
379 0 : if (*i == waiter && (*i)->Compare(tag)) {
380 0 : waiters_.erase(i);
381 0 : return true;
382 : }
383 : }
384 :
385 1418 : return false;
386 : }
387 :
388 : // -----------------------------------------------------------------------------
389 :
390 : } // namespace base
|