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