LibThreading: Add ThreadPool class

Add a simple thread pool with a fixed number of worker threads and a
shared work queue. The pool is accessed via ThreadPool::the() which
lazily creates a singleton with 4 worker threads.

submit() enqueues a work item and signals a condvar. Worker threads
loop waiting on the condvar, picking up and executing work items.

Worker threads use 8 MiB stacks to match the main thread, since
the JS parser can build deep call stacks during off-thread parsing.
This commit is contained in:
Andreas Kling 2026-02-24 20:03:58 +01:00 committed by Andreas Kling
parent a116f08acb
commit 8d234620bc
3 changed files with 91 additions and 0 deletions

View file

@ -1,6 +1,7 @@
set(SOURCES
BackgroundAction.cpp
Thread.cpp
ThreadPool.cpp
)
ladybird_lib(LibThreading threading)

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2026, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibThreading/ThreadPool.h>
static constexpr size_t THREAD_COUNT = 4;
static constexpr size_t THREAD_STACK_SIZE = 8 * MiB;
namespace Threading {
ThreadPool& ThreadPool::the()
{
static ThreadPool* instance = new ThreadPool;
return *instance;
}
ThreadPool::ThreadPool()
{
for (size_t i = 0; i < THREAD_COUNT; ++i) {
auto name = ByteString::formatted("Pool/{}", i);
auto thread = Thread::construct(name, [this]() -> intptr_t {
return worker_thread_func();
});
thread->set_stack_size(THREAD_STACK_SIZE);
thread->start();
m_threads.append(move(thread));
}
}
intptr_t ThreadPool::worker_thread_func()
{
while (true) {
Function<void()> work;
{
MutexLocker locker(m_mutex);
m_condition.wait_while([this] { return m_work_queue.is_empty(); });
work = m_work_queue.dequeue();
}
work();
}
}
void ThreadPool::submit(Function<void()> work)
{
MutexLocker locker(m_mutex);
m_work_queue.enqueue(move(work));
m_condition.signal();
}
}

View file

@ -0,0 +1,35 @@
/*
* Copyright (c) 2026, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Function.h>
#include <AK/Queue.h>
#include <AK/Vector.h>
#include <LibThreading/ConditionVariable.h>
#include <LibThreading/Mutex.h>
#include <LibThreading/Thread.h>
namespace Threading {
class ThreadPool {
public:
static ThreadPool& the();
void submit(Function<void()>);
private:
ThreadPool();
intptr_t worker_thread_func();
Mutex m_mutex;
ConditionVariable m_condition { m_mutex };
Queue<Function<void()>> m_work_queue;
Vector<NonnullRefPtr<Thread>> m_threads;
};
}