15#include <condition_variable>
27typedef std::function<void()>
Task;
43 std::shared_ptr<std::packaged_task<void()>>
ptr;
61 std::vector<std::thread> workers;
62 std::queue<Task> tasks;
64 std::condition_variable cv;
65 std::atomic<bool> stop;
76 std::unique_lock<std::mutex> lock(this->queue_mtx);
78 while (!this->stop && this->tasks.empty()) {
82 if (this->stop && this->tasks.empty())
return;
84 task = std::move(this->tasks.front());
97 for (
size_t i = 0; i < num_threads; ++i) {
98 workers.emplace_back(&ThreadPool_Advanced::workerLoop,
this);
110 auto enqueue(F f) -> std::future<
decltype(f())> {
111 using ReturnType =
decltype(f());
114 auto task = std::make_shared<std::packaged_task<ReturnType()>>(f);
116 std::future<ReturnType> res = task->get_future();
119 std::unique_lock<std::mutex> lock(queue_mtx);
121 tasks.emplace([task]() { (*task)(); });
136 for (std::thread &worker : workers) {
137 if (worker.joinable()) worker.join();
151 std::this_thread::sleep_for(std::chrono::milliseconds(500));
161 if (n <= 1)
return {
false, n};
162 for (
int i = 2; i * i <= n; i++) {
163 if (n % i == 0)
return {
false, n};
175 int persistent_threads = std::thread::hardware_concurrency();
177 std::cout <<
"Using " << persistent_threads <<
" threads for the program..." << std::endl;
184 std::cout <<
"Multiplication Result: " << result1.get() << std::endl;
std::pair< bool, int > isPrime(int n)
Checks if a number is prime.
int multiply(int a, int b)
Simulates an intensive multiplication operation.
std::mutex log_mtx
Global mutex for synchronized console logging. Prevents race conditions and interleaved output when m...
std::function< void()> Task
Type alias for a generic void-returning function. Used internally by the worker threads to process th...
int main()
Main entry point to demonstrate the Request-Response pattern.
A pool of persistent worker threads for concurrent task execution.
auto enqueue(F f) -> std::future< decltype(f())>
Adds a task to the pool and returns a future for the result.
~ThreadPool_Advanced()
Gracefully shuts down the thread pool.
ThreadPool_Advanced(size_t num_threads)
Initializes the thread pool with a specified number of threads.
A functor that wraps a packaged_task shared pointer.
std::shared_ptr< std::packaged_task< void()> > ptr
Pointer to the task.
void operator()()
Executes the wrapped task.