15#include <condition_variable>
25 std::function<void()>
func;
47 std::vector<std::thread> workers;
48 std::priority_queue<PriorityTask> tasks;
51 std::condition_variable cv;
52 std::atomic<bool> stop;
63 std::unique_lock<std::mutex> lock(this->queue_mtx);
66 while (!this->stop && this->tasks.empty()) {
71 if (this->stop && this->tasks.empty())
return;
74 pTask = std::move(
const_cast<PriorityTask&
>(this->tasks.top()));
87 for (
size_t i = 0; i < num_threads; ++i) {
88 workers.emplace_back(&PriorityThreadPool::workerLoop,
this);
97 void enqueue(
int priority, std::function<
void()> f) {
99 std::unique_lock<std::mutex> lock(queue_mtx);
100 tasks.push({priority, std::move(f)});
111 for (
auto &w : workers)
if (w.joinable()) w.join();
126 std::cout <<
"[Worker] Processing: " <<
type << std::endl;
127 std::this_thread::sleep_for(std::chrono::milliseconds(200));
139 std::cout <<
"Submitting tasks in random order...\n";
152 std::this_thread::sleep_for(std::chrono::seconds(2));
int main()
Main function demonstrating priority-based out-of-order execution.
A pool of worker threads that retrieves tasks based on priority.
~PriorityThreadPool()
Gracefully joins all worker threads after processing remaining tasks.
void enqueue(int priority, std::function< void()> f)
Submits a task with a specific priority level.
PriorityThreadPool(size_t num_threads)
Initializes the pool and starts worker threads.
A Functor simulating a financial processing task.
std::string type
Description of the payment activity.
void operator()() const
Executes the simulated payment task.
A wrapper for a callable task associated with a priority level.
int priority
Priority level (higher values indicate higher importance).
bool operator<(const PriorityTask &other) const
Comparator for the priority queue.
std::function< void()> func
The actual task/function to be executed.