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 "base/synchronization/waitable_event_watcher.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"
15 // -----------------------------------------------------------------------------
16 // WaitableEventWatcher (async waits).
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.
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...
28 // -----------------------------------------------------------------------------
29 // A thread-safe, reference-counted, write-once flag.
30 // -----------------------------------------------------------------------------
31 class Flag
: public RefCountedThreadSafe
<Flag
> {
33 Flag() { flag_
= false; }
36 AutoLock
locked(lock_
);
41 AutoLock
locked(lock_
);
46 friend class RefCountedThreadSafe
<Flag
>;
52 DISALLOW_COPY_AND_ASSIGN(Flag
);
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 // -----------------------------------------------------------------------------
59 class AsyncWaiter
: public WaitableEvent::Waiter
{
61 AsyncWaiter(MessageLoop
* message_loop
,
62 const base::Closure
& callback
,
64 : message_loop_(message_loop
),
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_
);
74 // We are removed from the wait-list by the WaitableEvent itself. It only
75 // remains to delete ourselves.
78 // We can always return true because an AsyncWaiter is never in two
79 // different wait-lists at the same time.
83 // See StopWatching for discussion
84 virtual bool Compare(void* tag
) OVERRIDE
{
85 return tag
== flag_
.get();
89 MessageLoop
*const message_loop_
;
90 base::Closure callback_
;
91 scoped_refptr
<Flag
> flag_
;
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 // -----------------------------------------------------------------------------
99 void 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
111 WaitableEventWatcher::WaitableEventWatcher()
112 : message_loop_(NULL
),
118 WaitableEventWatcher::~WaitableEventWatcher() {
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 // -----------------------------------------------------------------------------
126 bool 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";
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()) {
138 message_loop_
->RemoveDestructionObserver(this);
139 message_loop_
= NULL
;
145 DCHECK(!cancel_flag_
.get()) << "StartWatching called while still watching";
147 cancel_flag_
= new Flag
;
148 callback_
= callback
;
150 base::Bind(&AsyncCallbackHelper
, cancel_flag_
, callback_
, event
);
151 WaitableEvent::WaitableEventKernel
* kernel
= event
->kernel_
.get();
153 AutoLock
locked(kernel
->lock_
);
157 if (kernel
->signaled_
) {
158 if (!kernel
->manual_reset_
)
159 kernel
->signaled_
= false;
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_
);
167 message_loop_
= current_ml
;
168 current_ml
->AddDestructionObserver(this);
171 waiter_
= new AsyncWaiter(current_ml
, internal_callback_
, cancel_flag_
.get());
172 event
->Enqueue(waiter_
);
177 void WaitableEventWatcher::StopWatching() {
181 message_loop_
->RemoveDestructionObserver(this);
182 message_loop_
= NULL
;
185 if (!cancel_flag_
.get()) // if not currently watching...
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.
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
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.
209 AutoLock
locked(kernel_
->lock_
);
210 // We have a lock on the kernel. No one else can signal the event while we
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.
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
231 internal_callback_
.Reset();
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
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
248 // If the delegate has already been called then we have nothing to do. The
249 // task has been deleted by the MessageLoop.
252 WaitableEvent
* WaitableEventWatcher::GetWatchedEvent() {
253 if (!cancel_flag_
.get())
256 if (cancel_flag_
->value())
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 // -----------------------------------------------------------------------------
267 void WaitableEventWatcher::WillDestroyCurrentMessageLoop() {