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 mozilla_lazyidlethread_h__
8 #define mozilla_lazyidlethread_h__
10 #ifndef MOZILLA_INTERNAL_API
11 # error "This header is only usable from within libxul (MOZILLA_INTERNAL_API)."
14 #include "mozilla/TaskQueue.h"
15 #include "nsIObserver.h"
16 #include "nsThreadPool.h"
21 * This class provides a basic event target that creates its thread lazily and
22 * destroys its thread after a period of inactivity. It may be created and used
23 * on any thread but it may only be shut down from the thread on which it is
26 class LazyIdleThread final
: public nsISerialEventTarget
, public nsIObserver
{
28 NS_DECL_THREADSAFE_ISUPPORTS
29 NS_DECL_NSIEVENTTARGET_FULL
33 * If AutomaticShutdown is specified, and the LazyIdleThread is created on the
34 * main thread, Shutdown() will automatically be called during
35 * xpcom-shutdown-threads.
37 enum ShutdownMethod
{ AutomaticShutdown
= 0, ManualShutdown
};
40 * Create a new LazyIdleThread that will destroy its thread after the given
41 * number of milliseconds.
43 LazyIdleThread(uint32_t aIdleTimeoutMS
, const char* aName
,
44 ShutdownMethod aShutdownMethod
= AutomaticShutdown
);
47 * Shuts down the LazyIdleThread, waiting for any pending work to complete.
48 * Must be called from mOwningEventTarget.
53 * Register a nsIThreadPoolListener on the underlying threadpool to track the
54 * thread as it is created/destroyed.
56 nsresult
SetListener(nsIThreadPoolListener
* aListener
);
60 * Asynchronously shuts down the LazyIdleThread on mOwningEventTarget.
65 * The thread which created this LazyIdleThread and is responsible for
68 const nsCOMPtr
<nsISerialEventTarget
> mOwningEventTarget
;
71 * The single-thread backing threadpool which provides the actual threads used
72 * by LazyIdleThread, and implements the timeout.
74 const RefPtr
<nsThreadPool
> mThreadPool
;
77 * The serial event target providing a `nsISerialEventTarget` implementation
78 * when on the LazyIdleThread.
80 const RefPtr
<TaskQueue
> mTaskQueue
;
83 * Only safe to access on the owning thread or in the destructor (as no other
84 * threads have access then). If `true`, means the LazyIdleThread has already
85 * been shut down, so it does not need to be shut down asynchronously from the
88 bool mShutdown
= false;
91 } // namespace mozilla
93 #endif // mozilla_lazyidlethread_h__