class ThreadPool

Inherits: Module<ThreadPool>

Class that maintains a pool of threads we can easily retrieve and use for any task.

This saves on the cost of creating and destroying threads.

Public

Constructors

ThreadPool

ThreadPool(u32 threadCapacity, u32 idleTimeout = 60)

Constructs a new thread pool

threadCapacity
Default thread capacity, the pool will always try to keep this many threads available.
idleTimeout
(optional) How many seconds do threads need to be idle before we remove them from the pool.

Methods

~ThreadPool

virtual ~ThreadPool() noexcept

Run

SPtr<PooledThread> Run(const String &name, std::function<void ()> workerMethod)

Find an unused thread (or creates a new one) and runs the specified worker method on it.

name
A name you may use for more easily identifying the thread.
workerMethod
The worker method to be called by the thread.

Returns: A thread handle you may use for monitoring the thread execution.

StopAll

void StopAll()

Stops all threads and destroys them.

Caller must ensure each threads worker method returns otherwise this will never return.

ClearUnused

void ClearUnused()

Clear any unused threads that are over the capacity.

GetNumActive

u32 GetNumActive() const

Returns the number of running threads in the pool.

GetNumAllocated

u32 GetNumAllocated() const

Returns the total number of created threads in the pool (both running and unused).

staticInstance

static T &Instance()

Returns a reference to the module instance.

Module has to have been started up first otherwise an exception will be thrown.

staticInstancePtr

static T *InstancePtr()

Returns a pointer to the module instance.

Module has to have been started up first otherwise an exception will be thrown.

staticShutDown

static void ShutDown()

Shuts down this module and frees any resources it is using.

staticIsStarted

static bool IsStarted()

Query if the module has been started.

Protected

Methods

CreateThread

virtual SPtr<PooledThread> CreateThread(const String &name) = 0

Creates a new thread to be used by the pool.

GetThread

SPtr<PooledThread> GetThread(const String &name)

Returns the first unused thread if one exists, otherwise creates a new one.

name
Name to assign the thread.

~Module<T>

virtual ~Module<T>() = default

OnStartUp

virtual void OnStartUp()

Override if you want your module to be notified once it has been constructed and started.

OnShutDown

virtual void OnShutDown()

Override if you want your module to be notified just before it is deleted.

staticInstanceInternal

static T *&InstanceInternal()

Returns a singleton instance of this module.

staticIsDestroyed

static bool &IsDestroyed()

Checks has the Module been shut down.

staticIsStartedUp

static bool &IsStartedUp()

Checks has the Module been started up.

Fields

mThreads

Vector<SPtr<PooledThread>> mThreads

mDefaultCapacity

u32 mDefaultCapacity

mIdleTimeout

u32 mIdleTimeout

mAge

u32 mAge

unused check counter

mMutex

Mutex mMutex