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