14#include <condition_variable>
30 std::condition_variable cv;
39 std::lock_guard<std::mutex> lock(mtx);
50 std::unique_lock<std::mutex> lock(mtx);
52 cv.wait(lock, [
this] {
return !this->queue.empty(); });
53 T val = std::move(this->queue.front());
63typedef std::function<void()>
Task;
73 std::vector<std::thread> workers;
74 std::queue<Task> tasks;
76 std::condition_variable cv;
77 std::atomic<bool> stop;
86 std::unique_lock<std::mutex> lock(this->queue_mtx);
87 while (!this->stop && this->tasks.empty()) {
90 if (this->stop && this->tasks.empty())
return;
92 task = std::move(this->tasks.front());
105 for (
size_t i = 0; i < num_threads; ++i) {
106 workers.emplace_back(&ThreadPool::workerLoop,
this);
116 std::unique_lock<std::mutex> lock(queue_mtx);
117 tasks.push(std::move(t));
128 for (std::thread &worker : workers) {
129 if (worker.joinable()) worker.join();
150 if (
n <= 1) prime =
false;
152 for (
int i = 2; i * i <=
n; i++) {
169 int core_count = std::thread::hardware_concurrency();
173 std::cout <<
"System started with " << core_count <<
" workers.\n";
176 for (
int i = 1; i <= 500; ++i) {
184 for (
int i = 1; i <= 500; ++i) {
185 std::pair<bool, int> res = results.
pop();
187 std::cout <<
"[Main] Received Result: " << res.second <<
" is PRIME\n";
191 std::cout <<
"All tasks processed asynchronously!\n";
std::function< void()> Task
int main()
Orchestrates the mass calculation and collection of results.
std::function< void()> Task
Type alias for a generic void-returning function. Used internally by the worker threads to process th...
A thread-safe template queue used for inter-thread communication.
T pop()
Blocks until a result is available and then removes it from the queue.
void push(T result)
Pushes a result into the queue and notifies the waiting thread.
Manages a collection of threads that execute tasks from a shared queue.
~ThreadPool()
Joins all threads for a clean shutdown.
ThreadPool(size_t num_threads)
Constructs the pool and starts the worker threads.
void enqueue(Task t)
Enqueues a Task (functor/lambda) into the work queue.
A Functor (Function Object) that calculates primality.
int n
The number to check for primality.
void operator()() const
Overloaded operator() to perform the calculation.
ResultQueue< std::pair< bool, int > > * outputQueue
Pointer to the shared inbox.