mirror of
https://github.com/zoriya/nitro.git
synced 2026-10-13 00:05:23 +00:00
* feat: Create `Promise.hpp` * feat: Add `JSIConverter+Exception` * feat: Base for `Promise` and `Exception` * fix: Implement Exception conversion * Implement `Promise::awaitFuture` * Revive `+Future` * fix: Speed up creating `ThreadPool` * fix: Make `+Future` also just use `+Promise` impl * fix: Thread pool has 10 threads now. * feat: Allow `ThreadPool` to grow dynamically * chore: Format C++
61 lines
1.3 KiB
C++
61 lines
1.3 KiB
C++
//
|
|
// ThreadPool.hpp
|
|
// NitroModules
|
|
//
|
|
// Created by Marc Rousavy on 21.06.24.
|
|
//
|
|
|
|
#pragma once
|
|
|
|
#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* const name, size_t initialThreadCount);
|
|
~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:
|
|
void addThread();
|
|
|
|
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;
|
|
const char* _name;
|
|
static constexpr auto TAG = "ThreadPool";
|
|
};
|
|
|
|
} // namespace margelo::nitro
|