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