blob: 07ae694ad6711f6fce14dfc618bd31c916dd5c13 [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),
[email protected]9068bf92010-07-09 02:26:33125 waiter_(NULL),
[email protected]ac0efda2009-10-14 16:22:02126 callback_task_(NULL),
127 delegate_(NULL) {
[email protected]1c4947f2009-01-15 22:25:11128}
129
130WaitableEventWatcher::~WaitableEventWatcher() {
131 StopWatching();
132}
133
134// -----------------------------------------------------------------------------
135// The Handle is how the user cancels a wait. After deleting the Handle we
136// insure that the delegate cannot be called.
137// -----------------------------------------------------------------------------
138bool WaitableEventWatcher::StartWatching
139 (WaitableEvent* event, WaitableEventWatcher::Delegate* delegate) {
140 MessageLoop *const current_ml = MessageLoop::current();
141 DCHECK(current_ml) << "Cannot create WaitableEventWatcher without a "
142 "current MessageLoop";
143
[email protected]cc2aa412009-01-16 00:25:11144 // A user may call StartWatching from within the callback function. In this
145 // case, we won't know that we have finished watching, expect that the Flag
146 // will have been set in AsyncCallbackTask::Run()
147 if (cancel_flag_.get() && cancel_flag_->value()) {
148 if (message_loop_) {
149 message_loop_->RemoveDestructionObserver(this);
150 message_loop_ = NULL;
151 }
152
153 cancel_flag_ = NULL;
154 }
155
[email protected]1c4947f2009-01-15 22:25:11156 DCHECK(!cancel_flag_.get()) << "StartWatching called while still watching";
157
158 cancel_flag_ = new Flag;
159 callback_task_ = new AsyncCallbackTask(cancel_flag_, delegate, event);
[email protected]c891ab92009-03-26 18:28:19160 WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
[email protected]1c4947f2009-01-15 22:25:11161
[email protected]c891ab92009-03-26 18:28:19162 AutoLock locked(kernel->lock_);
[email protected]1c4947f2009-01-15 22:25:11163
[email protected]ac0efda2009-10-14 16:22:02164 delegate_ = delegate;
165 event_ = event;
166
[email protected]c891ab92009-03-26 18:28:19167 if (kernel->signaled_) {
168 if (!kernel->manual_reset_)
169 kernel->signaled_ = false;
[email protected]1c4947f2009-01-15 22:25:11170
171 // No hairpinning - we can't call the delegate directly here. We have to
172 // enqueue a task on the MessageLoop as normal.
173 current_ml->PostTask(FROM_HERE, callback_task_);
174 return true;
175 }
176
177 message_loop_ = current_ml;
178 current_ml->AddDestructionObserver(this);
179
[email protected]c891ab92009-03-26 18:28:19180 kernel_ = kernel;
[email protected]1c4947f2009-01-15 22:25:11181 waiter_ = new AsyncWaiter(current_ml, callback_task_, cancel_flag_);
182 event->Enqueue(waiter_);
183
184 return true;
185}
186
187void WaitableEventWatcher::StopWatching() {
[email protected]ac0efda2009-10-14 16:22:02188 delegate_ = NULL;
189
[email protected]1c4947f2009-01-15 22:25:11190 if (message_loop_) {
191 message_loop_->RemoveDestructionObserver(this);
192 message_loop_ = NULL;
193 }
194
195 if (!cancel_flag_.get()) // if not currently watching...
196 return;
197
[email protected]cc2aa412009-01-16 00:25:11198 if (cancel_flag_->value()) {
199 // In this case, the event has fired, but we haven't figured that out yet.
200 // The WaitableEvent may have been deleted too.
201 cancel_flag_ = NULL;
202 return;
203 }
204
[email protected]c891ab92009-03-26 18:28:19205 if (!kernel_.get()) {
206 // We have no kernel. This means that we never enqueued a Waiter on an
207 // event because the event was already signaled when StartWatching was
[email protected]1c4947f2009-01-15 22:25:11208 // called.
209 //
210 // In this case, a task was enqueued on the MessageLoop and will run.
211 // We set the flag in case the task hasn't yet run. The flag will stop the
212 // delegate getting called. If the task has run then we have the last
213 // reference to the flag and it will be deleted immedately after.
214 cancel_flag_->Set();
215 cancel_flag_ = NULL;
216 return;
217 }
218
[email protected]c891ab92009-03-26 18:28:19219 AutoLock locked(kernel_->lock_);
220 // We have a lock on the kernel. No one else can signal the event while we
221 // have it.
[email protected]1c4947f2009-01-15 22:25:11222
223 // We have a possible ABA issue here. If Dequeue was to compare only the
224 // pointer values then it's possible that the AsyncWaiter could have been
225 // fired, freed and the memory reused for a different Waiter which was
226 // enqueued in the same wait-list. We would think that that waiter was our
227 // AsyncWaiter and remove it.
228 //
229 // To stop this, Dequeue also takes a tag argument which is passed to the
230 // virtual Compare function before the two are considered a match. So we need
231 // a tag which is good for the lifetime of this handle: the Flag. Since we
232 // have a reference to the Flag, its memory cannot be reused while this object
233 // still exists. So if we find a waiter with the correct pointer value, and
234 // which shares a Flag pointer, we have a real match.
[email protected]c891ab92009-03-26 18:28:19235 if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
[email protected]1c4947f2009-01-15 22:25:11236 // Case 2: the waiter hasn't been signaled yet; it was still on the wait
237 // list. We've removed it, thus we can delete it and the task (which cannot
238 // have been enqueued with the MessageLoop because the waiter was never
239 // signaled)
240 delete waiter_;
241 delete callback_task_;
242 cancel_flag_ = NULL;
243 return;
244 }
245
246 // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may
247 // not have run yet, so we set the flag to tell it not to bother enqueuing the
248 // task on the MessageLoop, but to delete it instead. The Waiter deletes
249 // itself once run.
250 cancel_flag_->Set();
251 cancel_flag_ = NULL;
252
253 // If the waiter has already run then the task has been enqueued. If the Task
254 // hasn't yet run, the flag will stop the delegate from getting called. (This
255 // is thread safe because one may only delete a Handle from the MessageLoop
256 // thread.)
257 //
258 // If the delegate has already been called then we have nothing to do. The
259 // task has been deleted by the MessageLoop.
260}
261
262WaitableEvent* WaitableEventWatcher::GetWatchedEvent() {
263 if (!cancel_flag_.get())
264 return NULL;
265
266 if (cancel_flag_->value())
267 return NULL;
268
269 return event_;
270}
271
272// -----------------------------------------------------------------------------
273// This is called when the MessageLoop which the callback will be run it is
274// deleted. We need to cancel the callback as if we had been deleted, but we
275// will still be deleted at some point in the future.
276// -----------------------------------------------------------------------------
277void WaitableEventWatcher::WillDestroyCurrentMessageLoop() {
278 StopWatching();
279}
280
281} // namespace base