15#include <condition_variable>
23typedef std::function<void()>
Task;
38 std::vector<std::thread> workers;
39 std::queue<Task> tasks;
42 std::condition_variable cv;
43 std::atomic<bool> stop;
55 std::unique_lock<std::mutex> lock(this->queue_mtx);
58 while (!this->stop && this->tasks.empty()) {
63 if (this->stop && this->tasks.empty()) {
67 task = std::move(this->tasks.front());
84 for (
size_t i = 0; i < num_threads; ++i) {
85 workers.emplace_back(&ThreadPool::workerLoop,
this);
97 std::unique_lock<std::mutex> lock(queue_mtx);
98 tasks.push(std::move(t));
111 for (std::thread &worker : workers) {
112 if (worker.joinable()) {
125 std::lock_guard<std::mutex> lock(
log_mtx);
126 std::cout <<
"[Task " <<
id <<
"] is being processed by a worker..." << std::endl;
128 std::this_thread::sleep_for(std::chrono::milliseconds(300));
138 std::lock_guard<std::mutex> lock(
log_mtx);
139 std::cout <<
"--- System Initialized with 12 Worker Threads ---" << std::endl;
143 for (
int i = 1; i <= 1000; ++i) {
147 std::this_thread::sleep_for(std::chrono::seconds(5));
std::mutex log_mtx
Global mutex for synchronized console logging.
std::function< void()> Task
void dataProcessingTask(int id)
Simulates a CPU-bound data processing task.
int main()
Main function demonstrating mass task submission.
std::function< void()> Task
Manages a collection of threads that execute tasks from a shared queue.
~ThreadPool()
Destructor that ensures all threads finish current work before exiting.
ThreadPool(size_t num_threads)
Construct a new Thread Pool and spawns worker threads.
void enqueue(Task t)
Submits a task to the queue for execution.