Built as an exercise to understand job scheduling patterns in systems, this project implements a thread pool with priority order from scratch using C++11/14/17 primitives. This implementation allows tasks to jump the line based on a priority level.
Not all jobs are created equal. Some tasks need to be handled immediately, while others can wait. This project explores how to manage a fixed set of worker threads that pick the most important work based on the priority.
The project is split into two core components:
This is a simple wrapper for the work to be done. It stores:
- A name: For tracking and debugging.
- The function: Stored as a
std::function<void()>. - Priority: An integer where lower numbers indicate higher priority.
By defining how tasks compare to one another, the priority queue in the pool can automatically keep the most urgent task at the very top of the pile.
This is the orchestrator. When you initialize the pool, it starts a fixed number of worker threads.
-
Synchronization: I used a
std::mutexto ensure that multiple threads don't try to grab the same task at the same time. -
The Wait Mechanism: Instead of having threads constantly checking for work, I used a
std::condition_variable. Threads go to sleep when the queue is empty and are notified only when a new task is added or the pool is shutting down. -
The Worker Loop: Each thread runs an infinite loop that waits for a signal, pops the highest-priority task, and executes it.
-
Graceful Shutdown: The destructor sets a
stopflag and notifies all threads. The threads then finish any remaining tasks in the queue before joining back to the main thread.
Since this uses standard C++ threads, you can compile it with any modern compiler (GCC, Clang, or MSVC).
g++ -std=c++17 main.cpp -o threadpool -lpthread
./threadpoolUsing Makefile
to compile and link
make allto run
make runEnqueuing task: T#1 (Priority: 1)
Enqueuing task: T#2 (Priority: 9)
Executing task : T#1
Enqueuing task: T#3 (Priority: 8)
Enqueuing task: T#4 (Priority: 7)
Enqueuing task: T#5 (Priority: 6)
Enqueuing task: T#6 (Priority: 5)
Enqueuing task: T#7 (Priority: 4)
Enqueuing task: T#8 (Priority: 3)
Executing task : T#8
Product: 120
Executing task : T#7
Sum: 6
Executing task : T#6
Sum: 15
Product: Executing task : T#5
6
Executing task : T#4
Product: 120
Executing task : T#3
Sum: 6
Executing task : T#2
Sum: 15
Product: 6