Fix sort order of unlaunched apps on app list start page.
[chromium-blink-merge.git] / base / synchronization / waitable_event_watcher_posix.cc
blob6fc337cc81b420b504cef3be0d7194557082d86d
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"
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"
13 namespace base {
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> {
32 public:
33 Flag() { flag_ = false; }
35 void Set() {
36 AutoLock locked(lock_);
37 flag_ = true;
40 bool value() const {
41 AutoLock locked(lock_);
42 return flag_;
45 private:
46 friend class RefCountedThreadSafe<Flag>;
47 ~Flag() {}
49 mutable Lock lock_;
50 bool 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 {
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) { }
68 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.
76 delete this;
78 // We can always return true because an AsyncWaiter is never in two
79 // different wait-lists at the same time.
80 return true;
83 // See StopWatching for discussion
84 bool Compare(void* tag) override { return tag == flag_.get(); }
86 private:
87 MessageLoop *const message_loop_;
88 base::Closure callback_;
89 scoped_refptr<Flag> flag_;
92 // -----------------------------------------------------------------------------
93 // For async waits we need to make a callback in a MessageLoop thread. We do
94 // this by posting a callback, which calls the delegate and keeps track of when
95 // the event is canceled.
96 // -----------------------------------------------------------------------------
97 void AsyncCallbackHelper(Flag* flag,
98 const WaitableEventWatcher::EventCallback& callback,
99 WaitableEvent* event) {
100 // Runs in MessageLoop thread.
101 if (!flag->value()) {
102 // This is to let the WaitableEventWatcher know that the event has occured
103 // because it needs to be able to return NULL from GetWatchedObject
104 flag->Set();
105 callback.Run(event);
109 WaitableEventWatcher::WaitableEventWatcher()
110 : message_loop_(NULL),
111 cancel_flag_(NULL),
112 waiter_(NULL),
113 event_(NULL) {
116 WaitableEventWatcher::~WaitableEventWatcher() {
117 StopWatching();
120 // -----------------------------------------------------------------------------
121 // The Handle is how the user cancels a wait. After deleting the Handle we
122 // insure that the delegate cannot be called.
123 // -----------------------------------------------------------------------------
124 bool WaitableEventWatcher::StartWatching(
125 WaitableEvent* event,
126 const EventCallback& callback) {
127 MessageLoop *const current_ml = MessageLoop::current();
128 DCHECK(current_ml) << "Cannot create WaitableEventWatcher without a "
129 "current MessageLoop";
131 // A user may call StartWatching from within the callback function. In this
132 // case, we won't know that we have finished watching, expect that the Flag
133 // will have been set in AsyncCallbackHelper().
134 if (cancel_flag_.get() && cancel_flag_->value()) {
135 if (message_loop_) {
136 message_loop_->RemoveDestructionObserver(this);
137 message_loop_ = NULL;
140 cancel_flag_ = NULL;
143 DCHECK(!cancel_flag_.get()) << "StartWatching called while still watching";
145 cancel_flag_ = new Flag;
146 callback_ = callback;
147 internal_callback_ =
148 base::Bind(&AsyncCallbackHelper, cancel_flag_, callback_, event);
149 WaitableEvent::WaitableEventKernel* kernel = event->kernel_.get();
151 AutoLock locked(kernel->lock_);
153 event_ = event;
155 if (kernel->signaled_) {
156 if (!kernel->manual_reset_)
157 kernel->signaled_ = false;
159 // No hairpinning - we can't call the delegate directly here. We have to
160 // enqueue a task on the MessageLoop as normal.
161 current_ml->PostTask(FROM_HERE, internal_callback_);
162 return true;
165 message_loop_ = current_ml;
166 current_ml->AddDestructionObserver(this);
168 kernel_ = kernel;
169 waiter_ = new AsyncWaiter(current_ml, internal_callback_, cancel_flag_.get());
170 event->Enqueue(waiter_);
172 return true;
175 void WaitableEventWatcher::StopWatching() {
176 callback_.Reset();
178 if (message_loop_) {
179 message_loop_->RemoveDestructionObserver(this);
180 message_loop_ = NULL;
183 if (!cancel_flag_.get()) // if not currently watching...
184 return;
186 if (cancel_flag_->value()) {
187 // In this case, the event has fired, but we haven't figured that out yet.
188 // The WaitableEvent may have been deleted too.
189 cancel_flag_ = NULL;
190 return;
193 if (!kernel_.get()) {
194 // We have no kernel. This means that we never enqueued a Waiter on an
195 // event because the event was already signaled when StartWatching was
196 // called.
198 // In this case, a task was enqueued on the MessageLoop and will run.
199 // We set the flag in case the task hasn't yet run. The flag will stop the
200 // delegate getting called. If the task has run then we have the last
201 // reference to the flag and it will be deleted immedately after.
202 cancel_flag_->Set();
203 cancel_flag_ = NULL;
204 return;
207 AutoLock locked(kernel_->lock_);
208 // We have a lock on the kernel. No one else can signal the event while we
209 // have it.
211 // We have a possible ABA issue here. If Dequeue was to compare only the
212 // pointer values then it's possible that the AsyncWaiter could have been
213 // fired, freed and the memory reused for a different Waiter which was
214 // enqueued in the same wait-list. We would think that that waiter was our
215 // AsyncWaiter and remove it.
217 // To stop this, Dequeue also takes a tag argument which is passed to the
218 // virtual Compare function before the two are considered a match. So we need
219 // a tag which is good for the lifetime of this handle: the Flag. Since we
220 // have a reference to the Flag, its memory cannot be reused while this object
221 // still exists. So if we find a waiter with the correct pointer value, and
222 // which shares a Flag pointer, we have a real match.
223 if (kernel_->Dequeue(waiter_, cancel_flag_.get())) {
224 // Case 2: the waiter hasn't been signaled yet; it was still on the wait
225 // list. We've removed it, thus we can delete it and the task (which cannot
226 // have been enqueued with the MessageLoop because the waiter was never
227 // signaled)
228 delete waiter_;
229 internal_callback_.Reset();
230 cancel_flag_ = NULL;
231 return;
234 // Case 3: the waiter isn't on the wait-list, thus it was signaled. It may
235 // not have run yet, so we set the flag to tell it not to bother enqueuing the
236 // task on the MessageLoop, but to delete it instead. The Waiter deletes
237 // itself once run.
238 cancel_flag_->Set();
239 cancel_flag_ = NULL;
241 // If the waiter has already run then the task has been enqueued. If the Task
242 // hasn't yet run, the flag will stop the delegate from getting called. (This
243 // is thread safe because one may only delete a Handle from the MessageLoop
244 // thread.)
246 // If the delegate has already been called then we have nothing to do. The
247 // task has been deleted by the MessageLoop.
250 WaitableEvent* WaitableEventWatcher::GetWatchedEvent() {
251 if (!cancel_flag_.get())
252 return NULL;
254 if (cancel_flag_->value())
255 return NULL;
257 return event_;
260 // -----------------------------------------------------------------------------
261 // This is called when the MessageLoop which the callback will be run it is
262 // deleted. We need to cancel the callback as if we had been deleted, but we
263 // will still be deleted at some point in the future.
264 // -----------------------------------------------------------------------------
265 void WaitableEventWatcher::WillDestroyCurrentMessageLoop() {
266 StopWatching();
269 } // namespace base