• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "base/synchronization/waitable_event_watcher.h"
6 
7 #include <utility>
8 
9 #include "base/bind.h"
10 #include "base/logging.h"
11 #include "base/synchronization/lock.h"
12 #include "base/threading/sequenced_task_runner_handle.h"
13 
14 namespace base {
15 
16 // -----------------------------------------------------------------------------
17 // WaitableEventWatcher (async waits).
18 //
19 // The basic design is that we add an AsyncWaiter to the wait-list of the event.
20 // That AsyncWaiter has a pointer to SequencedTaskRunner, and a Task to be
21 // posted to it. The task ends up calling the callback when it runs on the
22 // sequence.
23 //
24 // Since the wait can be canceled, we have a thread-safe Flag object which is
25 // set when the wait has been canceled. At each stage in the above, we check the
26 // flag before going onto the next stage. Since the wait may only be canceled in
27 // the sequence which runs the Task, we are assured that the callback cannot be
28 // called after canceling...
29 
30 // -----------------------------------------------------------------------------
31 // A thread-safe, reference-counted, write-once flag.
32 // -----------------------------------------------------------------------------
33 class Flag : public RefCountedThreadSafe<Flag> {
34  public:
Flag()35   Flag() { flag_ = false; }
36 
Set()37   void Set() {
38     AutoLock locked(lock_);
39     flag_ = true;
40   }
41 
value() const42   bool value() const {
43     AutoLock locked(lock_);
44     return flag_;
45   }
46 
47  private:
48   friend class RefCountedThreadSafe<Flag>;
49   ~Flag() = default;
50 
51   mutable Lock lock_;
52   bool flag_;
53 
54   DISALLOW_COPY_AND_ASSIGN(Flag);
55 };
56 
57 // -----------------------------------------------------------------------------
58 // This is an asynchronous waiter which posts a task to a SequencedTaskRunner
59 // when fired. An AsyncWaiter may only be in a single wait-list.
60 // -----------------------------------------------------------------------------
61 class AsyncWaiter : public WaitableEvent::Waiter {
62  public:
AsyncWaiter(scoped_refptr<SequencedTaskRunner> task_runner,base::OnceClosure callback,Flag * flag)63   AsyncWaiter(scoped_refptr<SequencedTaskRunner> task_runner,
64               base::OnceClosure callback,
65               Flag* flag)
66       : task_runner_(std::move(task_runner)),
67         callback_(std::move(callback)),
68         flag_(flag) {}
69 
Fire(WaitableEvent * event)70   bool Fire(WaitableEvent* event) override {
71     // Post the callback if we haven't been cancelled.
72     if (!flag_->value())
73       task_runner_->PostTask(FROM_HERE, std::move(callback_));
74 
75     // We are removed from the wait-list by the WaitableEvent itself. It only
76     // remains to delete ourselves.
77     delete this;
78 
79     // We can always return true because an AsyncWaiter is never in two
80     // different wait-lists at the same time.
81     return true;
82   }
83 
84   // See StopWatching for discussion
Compare(void * tag)85   bool Compare(void* tag) override { return tag == flag_.get(); }
86 
87  private:
88   const scoped_refptr<SequencedTaskRunner> task_runner_;
89   base::OnceClosure callback_;
90   const scoped_refptr<Flag> flag_;
91 };
92 
93 // -----------------------------------------------------------------------------
94 // For async waits we need to run a callback on a sequence. We do this by
95 // posting an AsyncCallbackHelper task, which calls the callback and keeps track
96 // of when the event is canceled.
97 // -----------------------------------------------------------------------------
AsyncCallbackHelper(Flag * flag,WaitableEventWatcher::EventCallback callback,WaitableEvent * event)98 void AsyncCallbackHelper(Flag* flag,
99                          WaitableEventWatcher::EventCallback callback,
100                          WaitableEvent* event) {
101   // Runs on the sequence that called StartWatching().
102   if (!flag->value()) {
103     // This is to let the WaitableEventWatcher know that the event has occured.
104     flag->Set();
105     std::move(callback).Run(event);
106   }
107 }
108 
WaitableEventWatcher()109 WaitableEventWatcher::WaitableEventWatcher() {
110   sequence_checker_.DetachFromSequence();
111 }
112 
~WaitableEventWatcher()113 WaitableEventWatcher::~WaitableEventWatcher() {
114   // The destructor may be called from a different sequence than StartWatching()
115   // when there is no active watch. To avoid triggering a DCHECK in
116   // StopWatching(), do not call it when there is no active watch.
117   if (cancel_flag_ && !cancel_flag_->value())
118     StopWatching();
119 }
120 
121 // -----------------------------------------------------------------------------
122 // The Handle is how the user cancels a wait. After deleting the Handle we
123 // insure that the delegate cannot be called.
124 // -----------------------------------------------------------------------------
StartWatching(WaitableEvent * event,EventCallback callback,scoped_refptr<SequencedTaskRunner> task_runner)125 bool WaitableEventWatcher::StartWatching(
126     WaitableEvent* event,
127     EventCallback callback,
128     scoped_refptr<SequencedTaskRunner> task_runner) {
129   DCHECK(sequence_checker_.CalledOnValidSequence());
130 
131   // A user may call StartWatching from within the callback function. In this
132   // case, we won't know that we have finished watching, expect that the Flag
133   // will have been set in AsyncCallbackHelper().
134   if (cancel_flag_.get() && cancel_flag_->value())
135     cancel_flag_ = nullptr;
136 
137   DCHECK(!cancel_flag_) << "StartWatching called while still watching";
138 
139   cancel_flag_ = new Flag;
140   OnceClosure internal_callback =
141       base::BindOnce(&AsyncCallbackHelper, base::RetainedRef(cancel_flag_),
142                      std::move(callback), event);
143   WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
144 
145   AutoLock locked(kernel->lock_);
146 
147   if (kernel->signaled_) {
148     if (!kernel->manual_reset_)
149       kernel->signaled_ = false;
150 
151     // No hairpinning - we can't call the delegate directly here. We have to
152     // post a task to |task_runner| as usual.
153     task_runner->PostTask(FROM_HERE, std::move(internal_callback));
154     return true;
155   }
156 
157   kernel_ = kernel;
158   waiter_ = new AsyncWaiter(std::move(task_runner),
159                             std::move(internal_callback), cancel_flag_.get());
160   event->Enqueue(waiter_);
161 
162   return true;
163 }
164 
StopWatching()165 void WaitableEventWatcher::StopWatching() {
166   DCHECK(sequence_checker_.CalledOnValidSequence());
167 
168   if (!cancel_flag_.get())  // if not currently watching...
169     return;
170 
171   if (cancel_flag_->value()) {
172     // In this case, the event has fired, but we haven't figured that out yet.
173     // The WaitableEvent may have been deleted too.
174     cancel_flag_ = nullptr;
175     return;
176   }
177 
178   if (!kernel_.get()) {
179     // We have no kernel. This means that we never enqueued a Waiter on an
180     // event because the event was already signaled when StartWatching was
181     // called.
182     //
183     // In this case, a task was enqueued on the MessageLoop and will run.
184     // We set the flag in case the task hasn't yet run. The flag will stop the
185     // delegate getting called. If the task has run then we have the last
186     // reference to the flag and it will be deleted immedately after.
187     cancel_flag_->Set();
188     cancel_flag_ = nullptr;
189     return;
190   }
191 
192   AutoLock locked(kernel_->lock_);
193   // We have a lock on the kernel. No one else can signal the event while we
194   // have it.
195 
196   // We have a possible ABA issue here. If Dequeue was to compare only the
197   // pointer values then it's possible that the AsyncWaiter could have been
198   // fired, freed and the memory reused for a different Waiter which was
199   // enqueued in the same wait-list. We would think that that waiter was our
200   // AsyncWaiter and remove it.
201   //
202   // To stop this, Dequeue also takes a tag argument which is passed to the
203   // virtual Compare function before the two are considered a match. So we need
204   // a tag which is good for the lifetime of this handle: the Flag. Since we
205   // have a reference to the Flag, its memory cannot be reused while this object
206   // still exists. So if we find a waiter with the correct pointer value, and
207   // which shares a Flag pointer, we have a real match.
208   if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
209     // Case 2: the waiter hasn't been signaled yet; it was still on the wait
210     // list. We've removed it, thus we can delete it and the task (which cannot
211     // have been enqueued with the MessageLoop because the waiter was never
212     // signaled)
213     delete waiter_;
214     cancel_flag_ = nullptr;
215     return;
216   }
217 
218   // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may not
219   // have run yet, so we set the flag to tell it not to bother enqueuing the
220   // task on the SequencedTaskRunner, but to delete it instead. The Waiter
221   // deletes itself once run.
222   cancel_flag_->Set();
223   cancel_flag_ = nullptr;
224 
225   // If the waiter has already run then the task has been enqueued. If the Task
226   // hasn't yet run, the flag will stop the delegate from getting called. (This
227   // is thread safe because one may only delete a Handle from the sequence that
228   // called StartWatching()).
229   //
230   // If the delegate has already been called then we have nothing to do. The
231   // task has been deleted by the MessageLoop.
232 }
233 
234 }  // namespace base
235