C++ Concurrency Sandbox
Loading...
Searching...
No Matches
MessagePassing.cpp File Reference
#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <atomic>
#include <utility>
Include dependency graph for MessagePassing.cpp:

Go to the source code of this file.

Classes

class  ResultQueue< T >
 A thread-safe template queue used for inter-thread communication. More...
 
class  ThreadPool
 Manages a collection of threads that execute tasks from a shared queue. More...
 
struct  IsPrimeCalculator
 A Functor (Function Object) that calculates primality. More...
 

Typedefs

typedef std::function< void()> Task
 

Functions

int main ()
 Orchestrates the mass calculation and collection of results.
 

Typedef Documentation

◆ Task

typedef std::function<void()> Task

Definition at line 63 of file MessagePassing.cpp.

Function Documentation

◆ main()

int main ( void  )

Orchestrates the mass calculation and collection of results.

  • Uses the hardware concurrency count to optimize the thread pool size.

Definition at line 168 of file MessagePassing.cpp.

168 {
169 int core_count = std::thread::hardware_concurrency();
170 ThreadPool pool(core_count);
172
173 std::cout << "System started with " << core_count << " workers.\n";
174
175 // Submission: Asynchronous and non-blocking
176 for (int i = 1; i <= 500; ++i) {
177 IsPrimeCalculator taskObj;
178 taskObj.n = i;
179 taskObj.outputQueue = &results;
180 pool.enqueue(taskObj);
181 }
182
183 // Collection: The "Inbox" processing loop
184 for (int i = 1; i <= 500; ++i) {
185 std::pair<bool, int> res = results.pop();
186 if (res.first) {
187 std::cout << "[Main] Received Result: " << res.second << " is PRIME\n";
188 }
189 }
190
191 std::cout << "All tasks processed asynchronously!\n";
192 return 0;
193}
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.
Manages a collection of threads that execute tasks from a shared queue.
A Functor (Function Object) that calculates primality.
int n
The number to check for primality.
ResultQueue< std::pair< bool, int > > * outputQueue
Pointer to the shared inbox.

References ThreadPool::enqueue(), IsPrimeCalculator::n, IsPrimeCalculator::outputQueue, and ResultQueue< T >::pop().

Here is the call graph for this function: