C++ Concurrency Sandbox
Loading...
Searching...
No Matches
BasicThreadPool.cpp File Reference

A basic implementation of a persistent Worker Thread Pool. More...

#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <atomic>
#include <chrono>
Include dependency graph for BasicThreadPool.cpp:

Go to the source code of this file.

Classes

class  ThreadPool
 Manages a collection of threads that execute tasks from a shared queue. More...
 

Typedefs

typedef std::function< void()> Task
 

Functions

void dataProcessingTask (int id)
 Simulates a CPU-bound data processing task.
 
int main ()
 Main function demonstrating mass task submission.
 

Variables

std::mutex log_mtx
 Global mutex for synchronized console logging.
 

Detailed Description

A basic implementation of a persistent Worker Thread Pool.

  • This file demonstrates the core architecture of a thread pool: a fixed number of threads waiting on a shared task queue using a Monitor Pattern (Mutex + Condition Variable).

Definition in file BasicThreadPool.cpp.

Typedef Documentation

◆ Task

typedef std::function<void()> Task

Definition at line 23 of file BasicThreadPool.cpp.

Function Documentation

◆ dataProcessingTask()

void dataProcessingTask ( int  id)

Simulates a CPU-bound data processing task.

Parameters
idThe task identifier.

Definition at line 123 of file BasicThreadPool.cpp.

123 {
124 {
125 std::lock_guard<std::mutex> lock(log_mtx);
126 std::cout << "[Task " << id << "] is being processed by a worker..." << std::endl;
127 }
128 std::this_thread::sleep_for(std::chrono::milliseconds(300));
129}
std::mutex log_mtx
Global mutex for synchronized console logging.

References log_mtx.

Referenced by main().

Here is the caller graph for this function:

◆ main()

int main ( void  )

Main function demonstrating mass task submission.

Definition at line 134 of file BasicThreadPool.cpp.

134 {
135 ThreadPool pool(12);
136
137 {
138 std::lock_guard<std::mutex> lock(log_mtx);
139 std::cout << "--- System Initialized with 12 Worker Threads ---" << std::endl;
140 }
141
142 // Submit 1000 tasks
143 for (int i = 1; i <= 1000; ++i) {
144 pool.enqueue(std::bind(dataProcessingTask, i));
145 }
146
147 std::this_thread::sleep_for(std::chrono::seconds(5));
148
149 return 0;
150}
void dataProcessingTask(int id)
Simulates a CPU-bound data processing task.
Manages a collection of threads that execute tasks from a shared queue.

References dataProcessingTask(), ThreadPool::enqueue(), and log_mtx.

Here is the call graph for this function:

Variable Documentation

◆ log_mtx

std::mutex log_mtx

Global mutex for synchronized console logging.

Definition at line 28 of file BasicThreadPool.cpp.

Referenced by dataProcessingTask(), and main().