Bash++
Bash++ compiler internal documentation
ThreadPool.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2025 Andrew S. Rightenburg
3 * Bash++: Bash with classes
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 */
6
7#pragma once
8#include <atomic>
9#include <condition_variable>
10#include <functional>
11#include <mutex>
12#include <queue>
13#include <vector>
14#include <thread>
15
26 private:
27 std::vector<std::thread> workers;
28 std::queue<std::function<void()>> tasks;
29 std::mutex queue_mutex;
30 std::condition_variable condition;
31 bool stop = false;
32 std::atomic<bool> active{false}; // Whether the thread pool has accepted any tasks yet
33 public:
34 explicit ThreadPool(size_t threads = std::thread::hardware_concurrency());
36
37 ThreadPool(const ThreadPool& other) = delete; // Non-copyable
38 ThreadPool& operator=(const ThreadPool& other) = delete;
39 ThreadPool(ThreadPool&& other) noexcept = delete; // Non-movable
40 ThreadPool& operator=(ThreadPool&& other) noexcept = delete;
41
47 void enqueue(std::function<void()> task);
48 void cleanup();
49 size_t getThreadCount() const;
50 bool isActive() const;
51};
A thread pool implementation that manages a pool of worker threads to execute tasks concurrently.
Definition ThreadPool.h:25
bool stop
Definition ThreadPool.h:31
ThreadPool(const ThreadPool &other)=delete
~ThreadPool()
Definition ThreadPool.cpp:32
void enqueue(std::function< void()> task)
Enqueue a new task to be executed by the thread pool.
Definition ThreadPool.cpp:47
std::condition_variable condition
Definition ThreadPool.h:30
bool isActive() const
Definition ThreadPool.cpp:71
size_t getThreadCount() const
Definition ThreadPool.cpp:67
std::vector< std::thread > workers
Definition ThreadPool.h:27
void cleanup()
Definition ThreadPool.cpp:56
ThreadPool(ThreadPool &&other) noexcept=delete
ThreadPool & operator=(const ThreadPool &other)=delete
std::mutex queue_mutex
Definition ThreadPool.h:29
ThreadPool & operator=(ThreadPool &&other) noexcept=delete
std::queue< std::function< void()> > tasks
Definition ThreadPool.h:28
std::atomic< bool > active
Definition ThreadPool.h:32