Files
nitro/packages/react-native-nitro-modules/cpp/threading/ThreadPool.hpp
T
a4cf95da19 fix: Read _tasks.empty() under _queueMutex in ThreadPool::run() (#1413)
_tasks is a std::queue (backed by std::deque), not thread-safe.
Reading empty() outside the lock while worker threads call pop() and
run() itself calls push() is an unsynchronized access — a data race
caught by TSan. Move the check inside the existing lock scope and call
addThread() after releasing (since addThread() also takes _queueMutex).

Co-authored-by: Miklós Fazekas <boga@MBPM5P.local>
Co-authored-by: Marc Rousavy <me@mrousavy.com>
2026-06-24 16:10:04 +02:00

67 lines
1.6 KiB
C++

//
// ThreadPool.hpp
// NitroModules
//
// Created by Marc Rousavy on 21.06.24.
//
#pragma once
#include "NitroDefines.hpp"
#include <atomic>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
namespace margelo::nitro {
class ThreadPool final {
public:
/**
* Create a new ThreadPool with the given number of minimum workers/threads.
* The Thread Pool can expand on the fly if it is busy.
*/
explicit ThreadPool(const char* NON_NULL const name, size_t initialThreadsCount, size_t maxThreadsCount);
~ThreadPool();
ThreadPool(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
/**
* Schedules the given task asynchronously on the ThreadPool.
* It will run once a worker is available.
*/
void run(std::function<void()>&& task);
private:
/**
* Adds a new Thread to the current Thread Pool.
* This grows the size by one, and potentially starts work sooner if other Threads are busy.
*/
void addThread(std::unique_lock<std::mutex>& queueMutexLock);
public:
/**
* Get a static singleton instance - a shared ThreadPool.
* The shared ThreadPool has 3 threads.
*/
static ThreadPool& shared();
private:
std::vector<std::thread> _workers;
std::queue<std::function<void()>> _tasks;
std::mutex _queueMutex;
std::condition_variable _condition;
std::atomic<bool> _isAlive;
std::atomic<size_t> _threadCount;
size_t _threadCountLimit;
const char* NON_NULL _name;
static constexpr auto TAG = "ThreadPool";
};
} // namespace margelo::nitro