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