C++ Concurrency Sandbox
Loading...
Searching...
No Matches
PriorityThreadPool Class Reference

A pool of worker threads that retrieves tasks based on priority. More...

Collaboration diagram for PriorityThreadPool:

Public Member Functions

 PriorityThreadPool (size_t num_threads)
 Initializes the pool and starts worker threads.
 
void enqueue (int priority, std::function< void()> f)
 Submits a task with a specific priority level.
 
 ~PriorityThreadPool ()
 Gracefully joins all worker threads after processing remaining tasks.
 

Detailed Description

A pool of worker threads that retrieves tasks based on priority.

  • Unlike a standard FIFO (First-In-First-Out) thread pool, this class uses a heap-based queue to prioritize certain tasks over others.

Definition at line 45 of file Priority.cpp.

Constructor & Destructor Documentation

◆ PriorityThreadPool()

PriorityThreadPool::PriorityThreadPool ( size_t  num_threads)
inline

Initializes the pool and starts worker threads.

Parameters
num_threadsThe number of worker threads to maintain.

Definition at line 86 of file Priority.cpp.

86 : stop(false) {
87 for (size_t i = 0; i < num_threads; ++i) {
88 workers.emplace_back(&PriorityThreadPool::workerLoop, this);
89 }
90 }

◆ ~PriorityThreadPool()

PriorityThreadPool::~PriorityThreadPool ( )
inline

Gracefully joins all worker threads after processing remaining tasks.

Definition at line 108 of file Priority.cpp.

108 {
109 stop = true;
110 cv.notify_all();
111 for (auto &w : workers) if (w.joinable()) w.join();
112 }

Member Function Documentation

◆ enqueue()

void PriorityThreadPool::enqueue ( int  priority,
std::function< void()>  f 
)
inline

Submits a task with a specific priority level.

Parameters
priorityImportance level (e.g., 10 for urgent, 1 for background).
fThe function or lambda to execute.

Definition at line 97 of file Priority.cpp.

97 {
98 {
99 std::unique_lock<std::mutex> lock(queue_mtx);
100 tasks.push({priority, std::move(f)});
101 }
102 cv.notify_one();
103 }

Referenced by main().

Here is the caller graph for this function:

The documentation for this class was generated from the following file: