Bug 1874684 - Part 4: Prefer const references instead of copying Instant values....
[gecko.git] / xpcom / threads / TaskQueue.h
blob0d99d385d3e9e5e9697f32ed05dac6b65feb65c2
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef TaskQueue_h_
8 #define TaskQueue_h_
10 #include "mozilla/AbstractThread.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/Monitor.h"
13 #include "mozilla/MozPromise.h"
14 #include "mozilla/Queue.h"
15 #include "mozilla/RefPtr.h"
16 #include "mozilla/TaskDispatcher.h"
17 #include "mozilla/ThreadSafeWeakPtr.h"
18 #include "nsIDirectTaskDispatcher.h"
19 #include "nsThreadUtils.h"
21 namespace mozilla {
23 typedef MozPromise<bool, bool, false> ShutdownPromise;
25 class TaskQueueTrackerEntry;
27 // Abstracts executing runnables in order on an arbitrary event target. The
28 // runnables dispatched to the TaskQueue will be executed in the order in which
29 // they're received, and are guaranteed to not be executed concurrently.
30 // They may be executed on different threads, and a memory barrier is used
31 // to make this threadsafe for objects that aren't already threadsafe.
33 // Note, since a TaskQueue can also be converted to an nsIEventTarget using
34 // WrapAsEventTarget() its possible to construct a hierarchy of TaskQueues.
35 // Consider these three TaskQueues:
37 // TQ1 dispatches to the main thread
38 // TQ2 dispatches to TQ1
39 // TQ3 dispatches to TQ1
41 // This ensures there is only ever a single runnable from the entire chain on
42 // the main thread. It also ensures that TQ2 and TQ3 only have a single
43 // runnable in TQ1 at any time.
45 // This arrangement lets you prioritize work by dispatching runnables directly
46 // to TQ1. You can issue many runnables for important work. Meanwhile the TQ2
47 // and TQ3 work will always execute at most one runnable and then yield.
49 // A TaskQueue does not require explicit shutdown, however it provides a
50 // BeginShutdown() method that places TaskQueue in a shut down state and returns
51 // a promise that gets resolved once all pending tasks have completed
52 class TaskQueue final : public AbstractThread,
53 public nsIDirectTaskDispatcher,
54 public SupportsThreadSafeWeakPtr<TaskQueue> {
55 class EventTargetWrapper;
57 public:
58 NS_DECL_ISUPPORTS_INHERITED
59 NS_DECL_NSIDIRECTTASKDISPATCHER
60 MOZ_DECLARE_REFCOUNTED_TYPENAME(TaskQueue)
62 static RefPtr<TaskQueue> Create(already_AddRefed<nsIEventTarget> aTarget,
63 const char* aName,
64 bool aSupportsTailDispatch = false);
66 TaskDispatcher& TailDispatcher() override;
68 NS_IMETHOD Dispatch(already_AddRefed<nsIRunnable> aEvent,
69 uint32_t aFlags) override {
70 nsCOMPtr<nsIRunnable> runnable = aEvent;
72 MonitorAutoLock mon(mQueueMonitor);
73 return DispatchLocked(/* passed by ref */ runnable, aFlags,
74 NormalDispatch);
76 // If the ownership of |r| is not transferred in DispatchLocked() due to
77 // dispatch failure, it will be deleted here outside the lock. We do so
78 // since the destructor of the runnable might access TaskQueue and result
79 // in deadlocks.
82 [[nodiscard]] nsresult Dispatch(
83 already_AddRefed<nsIRunnable> aRunnable,
84 DispatchReason aReason = NormalDispatch) override {
85 nsCOMPtr<nsIRunnable> r = aRunnable;
87 MonitorAutoLock mon(mQueueMonitor);
88 return DispatchLocked(/* passed by ref */ r, NS_DISPATCH_NORMAL, aReason);
90 // If the ownership of |r| is not transferred in DispatchLocked() due to
91 // dispatch failure, it will be deleted here outside the lock. We do so
92 // since the destructor of the runnable might access TaskQueue and result
93 // in deadlocks.
96 // So we can access nsIEventTarget::Dispatch(nsIRunnable*, uint32_t aFlags)
97 using nsIEventTarget::Dispatch;
99 NS_IMETHOD RegisterShutdownTask(nsITargetShutdownTask* aTask) override;
100 NS_IMETHOD UnregisterShutdownTask(nsITargetShutdownTask* aTask) override;
102 using CancelPromise = MozPromise<bool, bool, false>;
104 // Puts the queue in a shutdown state and returns immediately. The queue will
105 // remain alive at least until all the events are drained, because the Runners
106 // hold a strong reference to the task queue, and one of them is always held
107 // by the target event queue when the task queue is non-empty.
109 // The returned promise is resolved when the queue goes empty.
110 RefPtr<ShutdownPromise> BeginShutdown();
112 // Blocks until all task finish executing.
113 void AwaitIdle();
115 // Blocks until the queue is flagged for shutdown and all tasks have finished
116 // executing.
117 void AwaitShutdownAndIdle();
119 bool IsEmpty();
121 // Returns true if the current thread is currently running a Runnable in
122 // the task queue.
123 bool IsCurrentThreadIn() const override;
124 using nsISerialEventTarget::IsOnCurrentThread;
126 private:
127 friend class SupportsThreadSafeWeakPtr<TaskQueue>;
129 TaskQueue(already_AddRefed<nsIEventTarget> aTarget, const char* aName,
130 bool aSupportsTailDispatch);
132 virtual ~TaskQueue();
134 // Blocks until all task finish executing. Called internally by methods
135 // that need to wait until the task queue is idle.
136 // mQueueMonitor must be held.
137 void AwaitIdleLocked();
139 nsresult DispatchLocked(nsCOMPtr<nsIRunnable>& aRunnable, uint32_t aFlags,
140 DispatchReason aReason = NormalDispatch);
142 void MaybeResolveShutdown();
144 nsCOMPtr<nsIEventTarget> mTarget MOZ_GUARDED_BY(mQueueMonitor);
146 // Handle for this TaskQueue being registered with our target if it implements
147 // TaskQueueTracker.
148 UniquePtr<TaskQueueTrackerEntry> mTrackerEntry MOZ_GUARDED_BY(mQueueMonitor);
150 // Monitor that protects the queue, mIsRunning, mIsShutdown and
151 // mShutdownTasks;
152 Monitor mQueueMonitor;
154 typedef struct TaskStruct {
155 nsCOMPtr<nsIRunnable> event;
156 uint32_t flags;
157 } TaskStruct;
159 // Queue of tasks to run.
160 Queue<TaskStruct> mTasks MOZ_GUARDED_BY(mQueueMonitor);
162 // List of tasks to run during shutdown.
163 nsTArray<nsCOMPtr<nsITargetShutdownTask>> mShutdownTasks
164 MOZ_GUARDED_BY(mQueueMonitor);
166 // The thread currently running the task queue. We store a reference
167 // to this so that IsCurrentThreadIn() can tell if the current thread
168 // is the thread currently running in the task queue.
170 // This may be read on any thread, but may only be written on mRunningThread.
171 // The thread can't die while we're running in it, and we only use it for
172 // pointer-comparison with the current thread anyway - so we make it atomic
173 // and don't refcount it.
174 Atomic<PRThread*> mRunningThread;
176 // RAII class that gets instantiated for each dispatched task.
177 class AutoTaskGuard {
178 public:
179 explicit AutoTaskGuard(TaskQueue* aQueue)
180 : mQueue(aQueue), mLastCurrentThread(nullptr) {
181 // NB: We don't hold the lock to aQueue here. Don't do anything that
182 // might require it.
183 MOZ_ASSERT(!mQueue->mTailDispatcher);
184 mTaskDispatcher.emplace(aQueue,
185 /* aIsTailDispatcher = */ true);
186 mQueue->mTailDispatcher = mTaskDispatcher.ptr();
188 mLastCurrentThread = sCurrentThreadTLS.get();
189 sCurrentThreadTLS.set(aQueue);
191 MOZ_ASSERT(mQueue->mRunningThread == nullptr);
192 mQueue->mRunningThread = PR_GetCurrentThread();
195 ~AutoTaskGuard() {
196 mTaskDispatcher->DrainDirectTasks();
197 mTaskDispatcher.reset();
199 MOZ_ASSERT(mQueue->mRunningThread == PR_GetCurrentThread());
200 mQueue->mRunningThread = nullptr;
202 sCurrentThreadTLS.set(mLastCurrentThread);
203 mQueue->mTailDispatcher = nullptr;
206 private:
207 Maybe<AutoTaskDispatcher> mTaskDispatcher;
208 TaskQueue* mQueue;
209 AbstractThread* mLastCurrentThread;
212 TaskDispatcher* mTailDispatcher;
214 // True if we've dispatched an event to the target to execute events from
215 // the queue.
216 bool mIsRunning MOZ_GUARDED_BY(mQueueMonitor);
218 // True if we've started our shutdown process.
219 bool mIsShutdown MOZ_GUARDED_BY(mQueueMonitor);
220 MozPromiseHolder<ShutdownPromise> mShutdownPromise
221 MOZ_GUARDED_BY(mQueueMonitor);
223 // The name of this TaskQueue. Useful when debugging dispatch failures.
224 const char* const mName;
226 SimpleTaskQueue mDirectTasks;
228 class Runner : public Runnable {
229 public:
230 explicit Runner(TaskQueue* aQueue)
231 : Runnable("TaskQueue::Runner"), mQueue(aQueue) {}
232 NS_IMETHOD Run() override;
234 private:
235 RefPtr<TaskQueue> mQueue;
239 #define MOZILLA_TASKQUEUETRACKER_IID \
241 0x765c4b56, 0xd5f6, 0x4a9f, { \
242 0x91, 0xcf, 0x51, 0x47, 0xb3, 0xc1, 0x7e, 0xa6 \
246 // XPCOM "interface" which may be implemented by nsIEventTarget implementations
247 // which want to keep track of what TaskQueue instances are currently targeting
248 // them. This may be used to asynchronously shutdown TaskQueues targeting a
249 // threadpool or other event target before the threadpool goes away.
251 // This explicitly TaskQueue-aware tracker is used instead of
252 // `nsITargetShutdownTask` as the operations required to shut down a TaskQueue
253 // are asynchronous, which is not a requirement of that interface.
254 class TaskQueueTracker : public nsISupports {
255 public:
256 NS_DECLARE_STATIC_IID_ACCESSOR(MOZILLA_TASKQUEUETRACKER_IID)
258 // Get a strong reference to every TaskQueue currently tracked by this
259 // TaskQueueTracker. May be called from any thraed.
260 nsTArray<RefPtr<TaskQueue>> GetAllTrackedTaskQueues();
262 protected:
263 virtual ~TaskQueueTracker();
265 private:
266 friend class TaskQueueTrackerEntry;
268 Mutex mMutex{"TaskQueueTracker"};
269 LinkedList<TaskQueueTrackerEntry> mEntries MOZ_GUARDED_BY(mMutex);
272 NS_DEFINE_STATIC_IID_ACCESSOR(TaskQueueTracker, MOZILLA_TASKQUEUETRACKER_IID)
274 } // namespace mozilla
276 #endif // TaskQueue_h_