Bug 1854550 - pt 12. Allow inlining between mozjemalloc and PHC r=glandium
[gecko.git] / xpcom / threads / nsThread.h
blobc38916d1a03fb0f4aacd707a40612953ac23c8dd
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 nsThread_h__
8 #define nsThread_h__
10 #include "MainThreadUtils.h"
11 #include "mozilla/AlreadyAddRefed.h"
12 #include "mozilla/Atomics.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/DataMutex.h"
15 #include "mozilla/EventQueue.h"
16 #include "mozilla/LinkedList.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "mozilla/Mutex.h"
19 #include "mozilla/NotNull.h"
20 #include "mozilla/RefPtr.h"
21 #include "mozilla/TaskDispatcher.h"
22 #include "mozilla/TimeStamp.h"
23 #include "mozilla/UniquePtr.h"
24 #include "nsIDirectTaskDispatcher.h"
25 #include "nsIEventTarget.h"
26 #include "nsISerialEventTarget.h"
27 #include "nsISupportsPriority.h"
28 #include "nsIThread.h"
29 #include "nsIThreadInternal.h"
30 #include "nsTArray.h"
32 namespace mozilla {
33 class CycleCollectedJSContext;
34 class DelayedRunnable;
35 class SynchronizedEventQueue;
36 class ThreadEventQueue;
37 class ThreadEventTarget;
39 template <typename T, size_t Length>
40 class Array;
41 } // namespace mozilla
43 using mozilla::NotNull;
45 class nsIRunnable;
46 class nsThreadShutdownContext;
48 // See https://www.w3.org/TR/longtasks
49 #define LONGTASK_BUSY_WINDOW_MS 50
51 // Time a Runnable executes before we accumulate telemetry on it
52 #define LONGTASK_TELEMETRY_MS 30
54 // A class for managing performance counter state.
55 namespace mozilla {
56 class PerformanceCounterState {
57 public:
58 explicit PerformanceCounterState(const uint32_t& aNestedEventLoopDepthRef,
59 bool aIsMainThread)
60 : mNestedEventLoopDepth(aNestedEventLoopDepthRef),
61 mIsMainThread(aIsMainThread),
62 // Does it really make sense to initialize these to "now" when we
63 // haven't run any tasks?
64 mLastLongTaskEnd(TimeStamp::Now()),
65 mLastLongNonIdleTaskEnd(mLastLongTaskEnd) {}
67 class Snapshot {
68 public:
69 Snapshot(uint32_t aOldEventLoopDepth, bool aOldIsIdleRunnable)
70 : mOldEventLoopDepth(aOldEventLoopDepth),
71 mOldIsIdleRunnable(aOldIsIdleRunnable) {}
73 Snapshot(const Snapshot&) = default;
74 Snapshot(Snapshot&&) = default;
76 private:
77 friend class PerformanceCounterState;
79 const uint32_t mOldEventLoopDepth;
80 const bool mOldIsIdleRunnable;
83 // Notification that a runnable is about to run. This captures a snapshot of
84 // our current state before we reset to prepare for the new runnable. This
85 // muast be called after mNestedEventLoopDepth has been incremented for the
86 // runnable execution. The performance counter passed in should be the one
87 // for the relevant runnable and may be null. aIsIdleRunnable should be true
88 // if and only if the runnable has idle priority.
89 Snapshot RunnableWillRun(TimeStamp aNow, bool aIsIdleRunnable);
91 // Notification that a runnable finished executing. This must be passed the
92 // snapshot that RunnableWillRun returned for the same runnable. This must be
93 // called before mNestedEventLoopDepth is decremented after the runnable's
94 // execution.
95 void RunnableDidRun(const nsCString& aName, Snapshot&& aSnapshot);
97 const TimeStamp& LastLongTaskEnd() const { return mLastLongTaskEnd; }
98 const TimeStamp& LastLongNonIdleTaskEnd() const {
99 return mLastLongNonIdleTaskEnd;
102 private:
103 // Called to report accumulated time, as needed, when we're about to run a
104 // runnable or just finished running one.
105 void MaybeReportAccumulatedTime(const nsCString& aName, TimeStamp aNow);
107 // Whether the runnable we are about to run, or just ran, is a nested
108 // runnable, in the sense that there is some other runnable up the stack
109 // spinning the event loop. This must be called before we change our
110 // mCurrentEventLoopDepth (when about to run a new event) or after we restore
111 // it (after we ran one).
112 bool IsNestedRunnable() const {
113 return mNestedEventLoopDepth > mCurrentEventLoopDepth;
116 // The event loop depth of the currently running runnable. Set to the max
117 // value of a uint32_t when there is no runnable running, so when starting to
118 // run a toplevel (not nested) runnable IsNestedRunnable() will test false.
119 uint32_t mCurrentEventLoopDepth = std::numeric_limits<uint32_t>::max();
121 // A reference to the nsThread's mNestedEventLoopDepth, so we can
122 // see what it is right now.
123 const uint32_t& mNestedEventLoopDepth;
125 // A boolean that indicates whether the currently running runnable is an idle
126 // runnable. Only has a useful value between RunnableWillRun() being called
127 // and RunnableDidRun() returning.
128 bool mCurrentRunnableIsIdleRunnable = false;
130 // Whether we're attached to the mainthread nsThread.
131 const bool mIsMainThread;
133 // The timestamp from which time to be accounted for should be measured. This
134 // can be the start of a runnable running or the end of a nested runnable
135 // running.
136 TimeStamp mCurrentTimeSliceStart;
138 // Information about when long tasks last ended.
139 TimeStamp mLastLongTaskEnd;
140 TimeStamp mLastLongNonIdleTaskEnd;
142 } // namespace mozilla
144 // A native thread
145 class nsThread : public nsIThreadInternal,
146 public nsISupportsPriority,
147 public nsIDirectTaskDispatcher,
148 private mozilla::LinkedListElement<nsThread> {
149 friend mozilla::LinkedList<nsThread>;
150 friend mozilla::LinkedListElement<nsThread>;
152 public:
153 NS_DECL_THREADSAFE_ISUPPORTS
154 NS_DECL_NSIEVENTTARGET_FULL
155 NS_DECL_NSITHREAD
156 NS_DECL_NSITHREADINTERNAL
157 NS_DECL_NSISUPPORTSPRIORITY
158 NS_DECL_NSIDIRECTTASKDISPATCHER
160 enum MainThreadFlag { MAIN_THREAD, NOT_MAIN_THREAD };
162 nsThread(NotNull<mozilla::SynchronizedEventQueue*> aQueue,
163 MainThreadFlag aMainThread,
164 nsIThreadManager::ThreadCreationOptions aOptions);
166 private:
167 nsThread();
169 public:
170 // Initialize this as a named wrapper for a new PRThread.
171 nsresult Init(const nsACString& aName);
173 // Initialize this as a wrapper for the current PRThread.
174 nsresult InitCurrentThread();
176 // Get this thread's name, thread-safe.
177 void GetThreadName(nsACString& aNameBuffer);
179 // Set this thread's name. Consider using
180 // NS_SetCurrentThreadName if you are not sure.
181 void SetThreadNameInternal(const nsACString& aName);
183 private:
184 // Initializes the mThreadId and stack base/size members, and adds the thread
185 // to the ThreadList().
186 void InitCommon();
188 public:
189 // The PRThread corresponding to this thread.
190 PRThread* GetPRThread() const { return mThread; }
192 const void* StackBase() const { return mStackBase; }
193 size_t StackSize() const { return mStackSize; }
195 uint32_t ThreadId() const { return mThreadId; }
197 // If this flag is true, then the nsThread was created using
198 // nsIThreadManager::NewThread.
199 bool ShutdownRequired() { return mShutdownRequired; }
201 // Lets GetRunningEventDelay() determine if the pool this is part
202 // of has an unstarted thread
203 void SetPoolThreadFreePtr(mozilla::Atomic<bool, mozilla::Relaxed>* aPtr) {
204 mIsAPoolThreadFree = aPtr;
207 void SetScriptObserver(mozilla::CycleCollectedJSContext* aScriptObserver);
209 uint32_t RecursionDepth() const;
211 void ShutdownComplete(NotNull<nsThreadShutdownContext*> aContext);
213 void WaitForAllAsynchronousShutdowns();
215 static const uint32_t kRunnableNameBufSize = 1000;
216 static mozilla::Array<char, kRunnableNameBufSize> sMainThreadRunnableName;
218 mozilla::SynchronizedEventQueue* EventQueue() { return mEvents.get(); }
220 bool ShuttingDown() const { return mShutdownContext != nullptr; }
222 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
224 // Returns the size of this object, its PRThread, and its shutdown contexts,
225 // but excluding its event queues.
226 size_t ShallowSizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
228 size_t SizeOfEventQueues(mozilla::MallocSizeOf aMallocSizeOf) const;
230 void SetUseHangMonitor(bool aValue) {
231 MOZ_ASSERT(IsOnCurrentThread());
232 mUseHangMonitor = aValue;
235 private:
236 void DoMainThreadSpecificProcessing() const;
238 protected:
239 friend class nsThreadShutdownEvent;
241 virtual ~nsThread();
243 static void ThreadFunc(void* aArg);
245 // Helper
246 already_AddRefed<nsIThreadObserver> GetObserver() {
247 nsIThreadObserver* obs;
248 nsThread::GetObserver(&obs);
249 return already_AddRefed<nsIThreadObserver>(obs);
252 already_AddRefed<nsThreadShutdownContext> ShutdownInternal(bool aSync);
254 friend class nsThreadManager;
255 friend class nsThreadPool;
257 void MaybeRemoveFromThreadList();
259 // Whether or not these members have a value determines whether the nsThread
260 // is treated as a full XPCOM thread or as a thin wrapper.
262 // For full nsThreads, they will always contain valid pointers. For thin
263 // wrappers around non-XPCOM threads, they will be null, and event dispatch
264 // methods which rely on them will fail (and assert) if called.
265 RefPtr<mozilla::SynchronizedEventQueue> mEvents;
266 RefPtr<mozilla::ThreadEventTarget> mEventTarget;
268 // The number of outstanding nsThreadShutdownContext started by this thread.
269 // The thread will not be allowed to exit until this number reaches 0.
270 uint32_t mOutstandingShutdownContexts;
271 // The shutdown context for ourselves.
272 RefPtr<nsThreadShutdownContext> mShutdownContext;
274 mozilla::CycleCollectedJSContext* mScriptObserver;
276 // Our name.
277 mozilla::DataMutex<nsCString> mThreadName;
279 void* mStackBase = nullptr;
280 uint32_t mStackSize;
281 uint32_t mThreadId;
283 uint32_t mNestedEventLoopDepth;
285 mozilla::Atomic<bool> mShutdownRequired;
287 int8_t mPriority;
289 const bool mIsMainThread;
290 bool mUseHangMonitor;
291 const bool mIsUiThread;
292 mozilla::Atomic<bool, mozilla::Relaxed>* mIsAPoolThreadFree;
294 // Set to true if this thread creates a JSRuntime.
295 bool mCanInvokeJS;
297 // The time the currently running event spent in event queues, and
298 // when it started running. If no event is running, they are
299 // TimeDuration() & TimeStamp().
300 mozilla::TimeDuration mLastEventDelay;
301 mozilla::TimeStamp mLastEventStart;
303 #ifdef EARLY_BETA_OR_EARLIER
304 nsCString mNameForWakeupTelemetry;
305 mozilla::TimeStamp mLastWakeupCheckTime;
306 uint32_t mWakeupCount = 0;
307 #endif
309 mozilla::PerformanceCounterState mPerformanceCounterState;
311 mozilla::SimpleTaskQueue mDirectTasks;
314 class nsThreadShutdownContext final : public nsIThreadShutdown {
315 public:
316 NS_DECL_THREADSAFE_ISUPPORTS
317 NS_DECL_NSITHREADSHUTDOWN
319 private:
320 friend class nsThread;
321 friend class nsThreadShutdownEvent;
322 friend class nsThreadShutdownAckEvent;
324 nsThreadShutdownContext(NotNull<nsThread*> aTerminatingThread,
325 nsThread* aJoiningThread)
326 : mTerminatingThread(aTerminatingThread),
327 mTerminatingPRThread(aTerminatingThread->GetPRThread()),
328 mJoiningThreadMutex("nsThreadShutdownContext::mJoiningThreadMutex"),
329 mJoiningThread(aJoiningThread) {}
331 ~nsThreadShutdownContext() = default;
333 // Must be called on the joining thread.
334 void MarkCompleted();
336 // NB: This may be the last reference.
337 NotNull<RefPtr<nsThread>> const mTerminatingThread;
338 PRThread* const mTerminatingPRThread;
340 // May only be accessed on the joining thread.
341 bool mCompleted = false;
342 nsTArray<nsCOMPtr<nsIRunnable>> mCompletionCallbacks;
344 // The thread waiting for this thread to shut down. Will either be cleared by
345 // the joining thread if `StopWaitingAndLeakThread` is called or by the
346 // terminating thread upon exiting and notifying the joining thread.
347 mozilla::Mutex mJoiningThreadMutex;
348 RefPtr<nsThread> mJoiningThread MOZ_GUARDED_BY(mJoiningThreadMutex);
349 bool mThreadLeaked MOZ_GUARDED_BY(mJoiningThreadMutex) = false;
352 #if defined(XP_UNIX) && !defined(ANDROID) && !defined(DEBUG) && HAVE_UALARM && \
353 defined(_GNU_SOURCE)
354 # define MOZ_CANARY
356 extern int sCanaryOutputFD;
357 #endif
359 #endif // nsThread_h__