Files
palemoon27/xpcom/threads/nsThreadPool.cpp
T
roytam1 e1c4d9e76f import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1077318 - call out to C++ for ARMv6 sub-word atomics. r=luke (2810c3f93)
- Bug 1142593 - factor atomics into the platform layer. r=waldo (f5088b2af)
- Bug 1173642 - Import unimplemented ARM64 Ion components. r=efaust (2567975a1)
- Bug 1170107 part 1 - Call GetProperty/CallProperty from the interpreter and Baseline. r=bhackett (fe45a446a)
- Bug 1170107 part 2 - Don't allocate a wrapper object for (pure) primitive.foo operations. r=bhackett (8793d7d2d)
- Bug 1152079 - Remove Purify support files. r=froydnj (69836c373)
- Bug 1152079 - Remove references to deleted Purify files from moz.build. r=bustage (ebd68a5fa)
- Bug 1126089 - Assert we don't Destroy nsFrameLoader in destructor (r=smaug) (c0894ed2b)
- Bug 1250871 - only send messages to child scripts when the docShell is still around. r=smaug (ac2562f55)
- Bug 1168750 - SharedStubs: (part3) Make split between baseline only and shared stubs, r=jandem (21c89cffe)
- Bug 1168750 - SharedStubs: (part4) Track for which engine a stub needs to get compiled, r=jandem (a36eb943b)
- Bug 1168753 - SharedStubs: Simplification to push BaselineFrame* in stubs, r=jandem (4a26b318d)
- pointer style (e20a50c7e)
- Bug 1169391 - Use a ReservedRooted class for optimized Rooted use in vm/Interpreter.cpp, r=terrence (1b80a857d)
- Bug 1182865 - Relax assertion on the allowed class for home objects, r=efaust (33009a9fe)
- Bug 1154391 - Update import declarations to current ES6 spec r=shu (ad7042d54)
- Bug 1154391 - Update parsing of export declarations to match current ES6 spec r=shu (4b509d9ec)
- Bug 1169171 - Split PNK_DELETE into several different kinds for each of the syntactically distinct modes of |delete| operation, depending upon the syntax of the operand. r=efaust (5667265fc)
- Bug 1169511 - Split PNK_TYPEOF into one kind for application to names one kind for application to other expressions. r=efaust (91a1086d8)
- pointer style (0546201d8)
- Bug 1163851 - Remove the remaining two tests of |pc->parsingForInit|, replacing them with yet another argument provided by the caller. r=efaust (919903e1e)
- Bug 1163851 - |pc->parsingForInit| is dead. Long live |InHandling|! r=efaust (bf35fb405)
- Bug 1167030 - Suppress MSVC warning C4661 in js/src. r=luke (1d28ed1d2)
- Bug 1167845 - Rejigger {in,de}crement/assignment parsing to vet targets primarily through a single Parser::isValidSimpleAssignmentTarget method, so that this method can also be called outside the parser. r=efaust (87484d3fc)
- Bug 1166950 - Introduce a new FunctionKind for class-constructors. r=efaust (e9dd197e1)
- Bug 1166950 - Make generator methods constructors. r=efaust (e076cacd6)
- Bug 1167845 - Rename ParseHandler::isName to ParseHandler::maybeName. r=efaust (1e090741b)
- Bug 1141865 - Part 3: Parse new.target, add Reflect support, and tests. (r=jorendorff, r=shu) (9e0282870)
- Bug 1139759 - Self-host %TypedArray%.prototype.copyWithin. r=till (8beea5f7c)
- pointer style (0da72f30a)
- Bug 1139769 - Add TypedArrayBuffer, TypedArrayByteOffset, and TypedArrayElementShift intrinsics to safely get the relevant information for a typed array. r=till (b5847a441)
- pointer style (5486dd33d)
- Bug 1139769 - Self-host %TypedArray%.prototype.subarray. r=t (b10c55e93)
- pointer style (335ab6c87)
- Bug 1140752 - Land code to self-host %TypedArray%.prototype.set, but don't enable it yet, pending perf-testing. This shouldn't make any changes to the build, except in terms of adding more code to it and affecting binary layout. r=jandem, also much feedback from till that effectively amounts to a review as well (98050308d)
- Bug 1144692: Fix --disable-ion builds; r=h4writer (3be32046c)
- Bug 1148970 - Check for possibly incomplete type sets when double checking the correctness of argument type set information, r=jandem. (934130c2e)
- bug 1171125 - Fix nsStackWalk to build for iOS. r=froydnj (c076c4d22)
- Bug 1119980 - Use 'snprintf' instead of 'sprintf' to avoid a warning on Lollipop-based builds. r=froydnj (a000af66c)
- Bug 1146597 - Avoid unnecessary calls to maybeSweep under hasUnanalyzedPreliminaryObjects, r=jandem. (335ba3fc3)
- Bug 1162134 - IonMonkey MIPS: Fix build failure on MIPS (js/src/jit/CodeGenerator.cpp:6740:28: error: `obj' was not declared in this scope). r=bhackett (56824379b)
- Bug 1160884 followup - Add testcase. r=me (5495ad016)
- Bug 1141865 - Part 4: Remove LCallDirectEvalV in anticipation of register pressure with new.target in eval frames. (r=jandem) (cbb706356)
- Bug 1162242 - Part 1: Remove instances of #ifdef PR_LOGGING. r=froydnj PR_LOGGING is now always defined, we can remove #ifdefs checking for it. (878131a4a)
- revert pointer style for patch (a263375f1)
- Bug 1144097. Fix yet another is<ScopeObject>() assert. r=shu (96d516117)
- Bug 1145282. Reverse the sense of IsValidTerminatingScope and rename it to IsSyntacticScope. r=luke (3681fc831)
- Bug 1149897 - PerformanceStatsService data is not monotonic. r=jandem (927639ac6)
- Bug 1142457 - Compute stopwatch durations per thread on MacOS X. r=jandem, r=areinald (a52c388be)
2020-10-02 18:15:14 +08:00

434 lines
11 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsIClassInfoImpl.h"
#include "nsThreadPool.h"
#include "nsThreadManager.h"
#include "nsThread.h"
#include "nsMemory.h"
#include "nsAutoPtr.h"
#include "prinrval.h"
#include "mozilla/Logging.h"
using namespace mozilla;
static PRLogModuleInfo*
GetThreadPoolLog()
{
static PRLogModuleInfo* sLog;
if (!sLog) {
sLog = PR_NewLogModule("nsThreadPool");
}
return sLog;
}
#ifdef LOG
#undef LOG
#endif
#define LOG(args) PR_LOG(GetThreadPoolLog(), PR_LOG_DEBUG, args)
// DESIGN:
// o Allocate anonymous threads.
// o Use nsThreadPool::Run as the main routine for each thread.
// o Each thread waits on the event queue's monitor, checking for
// pending events and rescheduling itself as an idle thread.
#define DEFAULT_THREAD_LIMIT 4
#define DEFAULT_IDLE_THREAD_LIMIT 1
#define DEFAULT_IDLE_THREAD_TIMEOUT PR_SecondsToInterval(60)
NS_IMPL_ADDREF(nsThreadPool)
NS_IMPL_RELEASE(nsThreadPool)
NS_IMPL_CLASSINFO(nsThreadPool, nullptr, nsIClassInfo::THREADSAFE,
NS_THREADPOOL_CID)
NS_IMPL_QUERY_INTERFACE_CI(nsThreadPool, nsIThreadPool, nsIEventTarget,
nsIRunnable)
NS_IMPL_CI_INTERFACE_GETTER(nsThreadPool, nsIThreadPool, nsIEventTarget)
nsThreadPool::nsThreadPool()
: mThreadLimit(DEFAULT_THREAD_LIMIT)
, mIdleThreadLimit(DEFAULT_IDLE_THREAD_LIMIT)
, mIdleThreadTimeout(DEFAULT_IDLE_THREAD_TIMEOUT)
, mIdleCount(0)
, mStackSize(nsIThreadManager::DEFAULT_STACK_SIZE)
, mShutdown(false)
{
}
nsThreadPool::~nsThreadPool()
{
// Threads keep a reference to the nsThreadPool until they return from Run()
// after removing themselves from mThreads.
MOZ_ASSERT(mThreads.IsEmpty());
}
nsresult
nsThreadPool::PutEvent(nsIRunnable* aEvent)
{
// Avoid spawning a new thread while holding the event queue lock...
bool spawnThread = false;
uint32_t stackSize = 0;
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
if (NS_WARN_IF(mShutdown)) {
return NS_ERROR_NOT_AVAILABLE;
}
LOG(("THRD-P(%p) put [%d %d %d]\n", this, mIdleCount, mThreads.Count(),
mThreadLimit));
MOZ_ASSERT(mIdleCount <= (uint32_t)mThreads.Count(), "oops");
// Make sure we have a thread to service this event.
if (mThreads.Count() < (int32_t)mThreadLimit &&
// Spawn a new thread if we don't have enough idle threads to serve
// pending events immediately.
mEvents.Count() >= mIdleCount) {
spawnThread = true;
}
mEvents.PutEvent(aEvent);
stackSize = mStackSize;
}
LOG(("THRD-P(%p) put [spawn=%d]\n", this, spawnThread));
if (!spawnThread) {
return NS_OK;
}
nsCOMPtr<nsIThread> thread;
nsThreadManager::get()->NewThread(0,
stackSize,
getter_AddRefs(thread));
if (NS_WARN_IF(!thread)) {
return NS_ERROR_UNEXPECTED;
}
bool killThread = false;
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
if (mThreads.Count() < (int32_t)mThreadLimit) {
mThreads.AppendObject(thread);
} else {
killThread = true; // okay, we don't need this thread anymore
}
}
LOG(("THRD-P(%p) put [%p kill=%d]\n", this, thread.get(), killThread));
if (killThread) {
// Pending events are processed on the current thread during
// nsIThread::Shutdown() execution, so if nsThreadPool::Dispatch() is called
// under caller's lock then deadlock could occur. This happens e.g. in case
// of nsStreamCopier. To prevent this situation, dispatch a shutdown event
// to the current thread instead of calling nsIThread::Shutdown() directly.
nsCOMPtr<nsIRunnable> r = NS_NewRunnableMethod(thread,
&nsIThread::Shutdown);
NS_DispatchToCurrentThread(r);
} else {
thread->Dispatch(this, NS_DISPATCH_NORMAL);
}
return NS_OK;
}
void
nsThreadPool::ShutdownThread(nsIThread* aThread)
{
LOG(("THRD-P(%p) shutdown async [%p]\n", this, aThread));
// This method is responsible for calling Shutdown on |aThread|. This must be
// done from some other thread, so we use the main thread of the application.
MOZ_ASSERT(!NS_IsMainThread(), "wrong thread");
nsCOMPtr<nsIRunnable> r = NS_NewRunnableMethod(aThread, &nsIThread::Shutdown);
NS_DispatchToMainThread(r);
}
NS_IMETHODIMP
nsThreadPool::Run()
{
LOG(("THRD-P(%p) enter\n", this));
mThreadNaming.SetThreadPoolName(mName);
nsCOMPtr<nsIThread> current;
nsThreadManager::get()->GetCurrentThread(getter_AddRefs(current));
bool shutdownThreadOnExit = false;
bool exitThread = false;
bool wasIdle = false;
PRIntervalTime idleSince;
nsCOMPtr<nsIThreadPoolListener> listener;
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
listener = mListener;
}
if (listener) {
listener->OnThreadCreated();
}
do {
nsCOMPtr<nsIRunnable> event;
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
if (!mEvents.GetPendingEvent(getter_AddRefs(event))) {
PRIntervalTime now = PR_IntervalNow();
PRIntervalTime timeout = PR_MillisecondsToInterval(mIdleThreadTimeout);
// If we are shutting down, then don't keep any idle threads
if (mShutdown) {
exitThread = true;
} else {
if (wasIdle) {
// if too many idle threads or idle for too long, then bail.
if (mIdleCount > mIdleThreadLimit || (now - idleSince) >= timeout) {
exitThread = true;
}
} else {
// if would be too many idle threads...
if (mIdleCount == mIdleThreadLimit) {
exitThread = true;
} else {
++mIdleCount;
idleSince = now;
wasIdle = true;
}
}
}
if (exitThread) {
if (wasIdle) {
--mIdleCount;
}
shutdownThreadOnExit = mThreads.RemoveObject(current);
} else {
PRIntervalTime delta = timeout - (now - idleSince);
LOG(("THRD-P(%p) waiting [%d]\n", this, delta));
#ifdef MOZ_NUWA_PROCESS
nsThreadManager::get()->SetThreadIdle(nullptr);
#endif // MOZ_NUWA_PROCESS
mon.Wait(delta);
}
} else if (wasIdle) {
wasIdle = false;
--mIdleCount;
}
}
if (event) {
LOG(("THRD-P(%p) running [%p]\n", this, event.get()));
#ifdef MOZ_NUWA_PROCESS
nsThreadManager::get()->SetThreadWorking();
#endif // MOZ_NUWA_PROCESS
event->Run();
}
} while (!exitThread);
if (listener) {
listener->OnThreadShuttingDown();
}
if (shutdownThreadOnExit) {
ShutdownThread(current);
}
LOG(("THRD-P(%p) leave\n", this));
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::Dispatch(nsIRunnable* aEvent, uint32_t aFlags)
{
LOG(("THRD-P(%p) dispatch [%p %x]\n", this, aEvent, aFlags));
if (NS_WARN_IF(mShutdown)) {
return NS_ERROR_NOT_AVAILABLE;
}
if (aFlags & DISPATCH_SYNC) {
nsCOMPtr<nsIThread> thread;
nsThreadManager::get()->GetCurrentThread(getter_AddRefs(thread));
if (NS_WARN_IF(!thread)) {
return NS_ERROR_NOT_AVAILABLE;
}
nsRefPtr<nsThreadSyncDispatch> wrapper =
new nsThreadSyncDispatch(thread, aEvent);
PutEvent(wrapper);
while (wrapper->IsPending()) {
NS_ProcessNextEvent(thread);
}
} else {
NS_ASSERTION(aFlags == NS_DISPATCH_NORMAL, "unexpected dispatch flags");
PutEvent(aEvent);
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::IsOnCurrentThread(bool* aResult)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
if (NS_WARN_IF(mShutdown)) {
return NS_ERROR_NOT_AVAILABLE;
}
nsIThread* thread = NS_GetCurrentThread();
for (uint32_t i = 0; i < static_cast<uint32_t>(mThreads.Count()); ++i) {
if (mThreads[i] == thread) {
*aResult = true;
return NS_OK;
}
}
*aResult = false;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::Shutdown()
{
nsCOMArray<nsIThread> threads;
nsCOMPtr<nsIThreadPoolListener> listener;
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
mShutdown = true;
mon.NotifyAll();
threads.AppendObjects(mThreads);
mThreads.Clear();
// Swap in a null listener so that we release the listener at the end of
// this method. The listener will be kept alive as long as the other threads
// that were created when it was set.
mListener.swap(listener);
}
// It's important that we shutdown the threads while outside the event queue
// monitor. Otherwise, we could end up dead-locking.
for (int32_t i = 0; i < threads.Count(); ++i) {
threads[i]->Shutdown();
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::GetThreadLimit(uint32_t* aValue)
{
*aValue = mThreadLimit;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetThreadLimit(uint32_t aValue)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
mThreadLimit = aValue;
if (mIdleThreadLimit > mThreadLimit) {
mIdleThreadLimit = mThreadLimit;
}
if (static_cast<uint32_t>(mThreads.Count()) > mThreadLimit) {
mon.NotifyAll(); // wake up threads so they observe this change
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::GetIdleThreadLimit(uint32_t* aValue)
{
*aValue = mIdleThreadLimit;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetIdleThreadLimit(uint32_t aValue)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
mIdleThreadLimit = aValue;
if (mIdleThreadLimit > mThreadLimit) {
mIdleThreadLimit = mThreadLimit;
}
// Do we need to kill some idle threads?
if (mIdleCount > mIdleThreadLimit) {
mon.NotifyAll(); // wake up threads so they observe this change
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::GetIdleThreadTimeout(uint32_t* aValue)
{
*aValue = mIdleThreadTimeout;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetIdleThreadTimeout(uint32_t aValue)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
uint32_t oldTimeout = mIdleThreadTimeout;
mIdleThreadTimeout = aValue;
// Do we need to notify any idle threads that their sleep time has shortened?
if (mIdleThreadTimeout < oldTimeout && mIdleCount > 0) {
mon.NotifyAll(); // wake up threads so they observe this change
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::GetThreadStackSize(uint32_t* aValue)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
*aValue = mStackSize;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetThreadStackSize(uint32_t aValue)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
mStackSize = aValue;
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::GetListener(nsIThreadPoolListener** aListener)
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
NS_IF_ADDREF(*aListener = mListener);
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetListener(nsIThreadPoolListener* aListener)
{
nsCOMPtr<nsIThreadPoolListener> swappedListener(aListener);
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
mListener.swap(swappedListener);
}
return NS_OK;
}
NS_IMETHODIMP
nsThreadPool::SetName(const nsACString& aName)
{
{
ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor());
if (mThreads.Count()) {
return NS_ERROR_NOT_AVAILABLE;
}
}
mName = aName;
return NS_OK;
}