Create watch list entry 'midi' and add myself to the list
[chromium-blink-merge.git] / base / synchronization / waitable_event_posix.cc
blob04a262b721d80186011c2d5e3370396805765d6c
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 <algorithm>
6 #include <vector>
8 #include "base/logging.h"
9 #include "base/synchronization/waitable_event.h"
10 #include "base/synchronization/condition_variable.h"
11 #include "base/synchronization/lock.h"
12 #include "base/threading/thread_restrictions.h"
14 // -----------------------------------------------------------------------------
15 // A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
16 // support cross-process events (where one process can signal an event which
17 // others are waiting on). Because of this, we can avoid having one thread per
18 // listener in several cases.
20 // The WaitableEvent maintains a list of waiters, protected by a lock. Each
21 // waiter is either an async wait, in which case we have a Task and the
22 // MessageLoop to run it on, or a blocking wait, in which case we have the
23 // condition variable to signal.
25 // Waiting involves grabbing the lock and adding oneself to the wait list. Async
26 // waits can be canceled, which means grabbing the lock and removing oneself
27 // from the list.
29 // Waiting on multiple events is handled by adding a single, synchronous wait to
30 // the wait-list of many events. An event passes a pointer to itself when
31 // firing a waiter and so we can store that pointer to find out which event
32 // triggered.
33 // -----------------------------------------------------------------------------
35 namespace base {
37 // -----------------------------------------------------------------------------
38 // This is just an abstract base class for waking the two types of waiters
39 // -----------------------------------------------------------------------------
40 WaitableEvent::WaitableEvent(bool manual_reset, bool initially_signaled)
41 : kernel_(new WaitableEventKernel(manual_reset, initially_signaled)) {
44 WaitableEvent::~WaitableEvent() {
47 void WaitableEvent::Reset() {
48 base::AutoLock locked(kernel_->lock_);
49 kernel_->signaled_ = false;
52 void WaitableEvent::Signal() {
53 base::AutoLock locked(kernel_->lock_);
55 if (kernel_->signaled_)
56 return;
58 if (kernel_->manual_reset_) {
59 SignalAll();
60 kernel_->signaled_ = true;
61 } else {
62 // In the case of auto reset, if no waiters were woken, we remain
63 // signaled.
64 if (!SignalOne())
65 kernel_->signaled_ = true;
69 bool WaitableEvent::IsSignaled() {
70 base::AutoLock locked(kernel_->lock_);
72 const bool result = kernel_->signaled_;
73 if (result && !kernel_->manual_reset_)
74 kernel_->signaled_ = false;
75 return result;
78 // -----------------------------------------------------------------------------
79 // Synchronous waits
81 // -----------------------------------------------------------------------------
82 // This is a synchronous waiter. The thread is waiting on the given condition
83 // variable and the fired flag in this object.
84 // -----------------------------------------------------------------------------
85 class SyncWaiter : public WaitableEvent::Waiter {
86 public:
87 SyncWaiter()
88 : fired_(false),
89 signaling_event_(NULL),
90 lock_(),
91 cv_(&lock_) {
94 bool Fire(WaitableEvent* signaling_event) override {
95 base::AutoLock locked(lock_);
97 if (fired_)
98 return false;
100 fired_ = true;
101 signaling_event_ = signaling_event;
103 cv_.Broadcast();
105 // Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on
106 // the blocking thread's stack. There is no |delete this;| in Fire. The
107 // SyncWaiter object is destroyed when it goes out of scope.
109 return true;
112 WaitableEvent* signaling_event() const {
113 return signaling_event_;
116 // ---------------------------------------------------------------------------
117 // These waiters are always stack allocated and don't delete themselves. Thus
118 // there's no problem and the ABA tag is the same as the object pointer.
119 // ---------------------------------------------------------------------------
120 bool Compare(void* tag) override { return this == tag; }
122 // ---------------------------------------------------------------------------
123 // Called with lock held.
124 // ---------------------------------------------------------------------------
125 bool fired() const {
126 return fired_;
129 // ---------------------------------------------------------------------------
130 // During a TimedWait, we need a way to make sure that an auto-reset
131 // WaitableEvent doesn't think that this event has been signaled between
132 // unlocking it and removing it from the wait-list. Called with lock held.
133 // ---------------------------------------------------------------------------
134 void Disable() {
135 fired_ = true;
138 base::Lock* lock() {
139 return &lock_;
142 base::ConditionVariable* cv() {
143 return &cv_;
146 private:
147 bool fired_;
148 WaitableEvent* signaling_event_; // The WaitableEvent which woke us
149 base::Lock lock_;
150 base::ConditionVariable cv_;
153 void WaitableEvent::Wait() {
154 bool result = TimedWait(TimeDelta::Max());
155 DCHECK(result) << "TimedWait() should never fail with infinite timeout";
158 bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
159 DCHECK_GE(max_time, TimeDelta());
160 base::ThreadRestrictions::AssertWaitAllowed();
161 const TimeTicks end_time(TimeTicks::Now() + max_time);
163 kernel_->lock_.Acquire();
164 if (kernel_->signaled_) {
165 if (!kernel_->manual_reset_) {
166 // In this case we were signaled when we had no waiters. Now that
167 // someone has waited upon us, we can automatically reset.
168 kernel_->signaled_ = false;
171 kernel_->lock_.Release();
172 return true;
175 SyncWaiter sw;
176 sw.lock()->Acquire();
178 Enqueue(&sw);
179 kernel_->lock_.Release();
180 // We are violating locking order here by holding the SyncWaiter lock but not
181 // the WaitableEvent lock. However, this is safe because we don't lock @lock_
182 // again before unlocking it.
184 for (;;) {
185 const TimeTicks current_time(TimeTicks::Now());
187 if (sw.fired() || current_time >= end_time) {
188 const bool return_value = sw.fired();
190 // We can't acquire @lock_ before releasing the SyncWaiter lock (because
191 // of locking order), however, in between the two a signal could be fired
192 // and @sw would accept it, however we will still return false, so the
193 // signal would be lost on an auto-reset WaitableEvent. Thus we call
194 // Disable which makes sw::Fire return false.
195 sw.Disable();
196 sw.lock()->Release();
198 // This is a bug that has been enshrined in the interface of
199 // WaitableEvent now: |Dequeue| is called even when |sw.fired()| is true,
200 // even though it'll always return false in that case. However, taking
201 // the lock ensures that |Signal| has completed before we return and
202 // means that a WaitableEvent can synchronise its own destruction.
203 kernel_->lock_.Acquire();
204 kernel_->Dequeue(&sw, &sw);
205 kernel_->lock_.Release();
207 return return_value;
210 sw.cv()->TimedWait(end_time - current_time);
214 // -----------------------------------------------------------------------------
215 // Synchronous waiting on multiple objects.
217 static bool // StrictWeakOrdering
218 cmp_fst_addr(const std::pair<WaitableEvent*, unsigned> &a,
219 const std::pair<WaitableEvent*, unsigned> &b) {
220 return a.first < b.first;
223 // static
224 size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables,
225 size_t count) {
226 base::ThreadRestrictions::AssertWaitAllowed();
227 DCHECK(count) << "Cannot wait on no events";
229 // We need to acquire the locks in a globally consistent order. Thus we sort
230 // the array of waitables by address. We actually sort a pairs so that we can
231 // map back to the original index values later.
232 std::vector<std::pair<WaitableEvent*, size_t> > waitables;
233 waitables.reserve(count);
234 for (size_t i = 0; i < count; ++i)
235 waitables.push_back(std::make_pair(raw_waitables[i], i));
237 DCHECK_EQ(count, waitables.size());
239 sort(waitables.begin(), waitables.end(), cmp_fst_addr);
241 // The set of waitables must be distinct. Since we have just sorted by
242 // address, we can check this cheaply by comparing pairs of consecutive
243 // elements.
244 for (size_t i = 0; i < waitables.size() - 1; ++i) {
245 DCHECK(waitables[i].first != waitables[i+1].first);
248 SyncWaiter sw;
250 const size_t r = EnqueueMany(&waitables[0], count, &sw);
251 if (r) {
252 // One of the events is already signaled. The SyncWaiter has not been
253 // enqueued anywhere. EnqueueMany returns the count of remaining waitables
254 // when the signaled one was seen, so the index of the signaled event is
255 // @count - @r.
256 return waitables[count - r].second;
259 // At this point, we hold the locks on all the WaitableEvents and we have
260 // enqueued our waiter in them all.
261 sw.lock()->Acquire();
262 // Release the WaitableEvent locks in the reverse order
263 for (size_t i = 0; i < count; ++i) {
264 waitables[count - (1 + i)].first->kernel_->lock_.Release();
267 for (;;) {
268 if (sw.fired())
269 break;
271 sw.cv()->Wait();
273 sw.lock()->Release();
275 // The address of the WaitableEvent which fired is stored in the SyncWaiter.
276 WaitableEvent *const signaled_event = sw.signaling_event();
277 // This will store the index of the raw_waitables which fired.
278 size_t signaled_index = 0;
280 // Take the locks of each WaitableEvent in turn (except the signaled one) and
281 // remove our SyncWaiter from the wait-list
282 for (size_t i = 0; i < count; ++i) {
283 if (raw_waitables[i] != signaled_event) {
284 raw_waitables[i]->kernel_->lock_.Acquire();
285 // There's no possible ABA issue with the address of the SyncWaiter here
286 // because it lives on the stack. Thus the tag value is just the pointer
287 // value again.
288 raw_waitables[i]->kernel_->Dequeue(&sw, &sw);
289 raw_waitables[i]->kernel_->lock_.Release();
290 } else {
291 // By taking this lock here we ensure that |Signal| has completed by the
292 // time we return, because |Signal| holds this lock. This matches the
293 // behaviour of |Wait| and |TimedWait|.
294 raw_waitables[i]->kernel_->lock_.Acquire();
295 raw_waitables[i]->kernel_->lock_.Release();
296 signaled_index = i;
300 return signaled_index;
303 // -----------------------------------------------------------------------------
304 // If return value == 0:
305 // The locks of the WaitableEvents have been taken in order and the Waiter has
306 // been enqueued in the wait-list of each. None of the WaitableEvents are
307 // currently signaled
308 // else:
309 // None of the WaitableEvent locks are held. The Waiter has not been enqueued
310 // in any of them and the return value is the index of the first WaitableEvent
311 // which was signaled, from the end of the array.
312 // -----------------------------------------------------------------------------
313 // static
314 size_t WaitableEvent::EnqueueMany
315 (std::pair<WaitableEvent*, size_t>* waitables,
316 size_t count, Waiter* waiter) {
317 if (!count)
318 return 0;
320 waitables[0].first->kernel_->lock_.Acquire();
321 if (waitables[0].first->kernel_->signaled_) {
322 if (!waitables[0].first->kernel_->manual_reset_)
323 waitables[0].first->kernel_->signaled_ = false;
324 waitables[0].first->kernel_->lock_.Release();
325 return count;
328 const size_t r = EnqueueMany(waitables + 1, count - 1, waiter);
329 if (r) {
330 waitables[0].first->kernel_->lock_.Release();
331 } else {
332 waitables[0].first->Enqueue(waiter);
335 return r;
338 // -----------------------------------------------------------------------------
341 // -----------------------------------------------------------------------------
342 // Private functions...
344 WaitableEvent::WaitableEventKernel::WaitableEventKernel(bool manual_reset,
345 bool initially_signaled)
346 : manual_reset_(manual_reset),
347 signaled_(initially_signaled) {
350 WaitableEvent::WaitableEventKernel::~WaitableEventKernel() {
353 // -----------------------------------------------------------------------------
354 // Wake all waiting waiters. Called with lock held.
355 // -----------------------------------------------------------------------------
356 bool WaitableEvent::SignalAll() {
357 bool signaled_at_least_one = false;
359 for (std::list<Waiter*>::iterator
360 i = kernel_->waiters_.begin(); i != kernel_->waiters_.end(); ++i) {
361 if ((*i)->Fire(this))
362 signaled_at_least_one = true;
365 kernel_->waiters_.clear();
366 return signaled_at_least_one;
369 // ---------------------------------------------------------------------------
370 // Try to wake a single waiter. Return true if one was woken. Called with lock
371 // held.
372 // ---------------------------------------------------------------------------
373 bool WaitableEvent::SignalOne() {
374 for (;;) {
375 if (kernel_->waiters_.empty())
376 return false;
378 const bool r = (*kernel_->waiters_.begin())->Fire(this);
379 kernel_->waiters_.pop_front();
380 if (r)
381 return true;
385 // -----------------------------------------------------------------------------
386 // Add a waiter to the list of those waiting. Called with lock held.
387 // -----------------------------------------------------------------------------
388 void WaitableEvent::Enqueue(Waiter* waiter) {
389 kernel_->waiters_.push_back(waiter);
392 // -----------------------------------------------------------------------------
393 // Remove a waiter from the list of those waiting. Return true if the waiter was
394 // actually removed. Called with lock held.
395 // -----------------------------------------------------------------------------
396 bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) {
397 for (std::list<Waiter*>::iterator
398 i = waiters_.begin(); i != waiters_.end(); ++i) {
399 if (*i == waiter && (*i)->Compare(tag)) {
400 waiters_.erase(i);
401 return true;
405 return false;
408 // -----------------------------------------------------------------------------
410 } // namespace base