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

Go to the source code of this file.

Classes

struct  AgedTask
 Represents a task whose priority can increase over time. More...
 
class  AgingPriorityPool
 A priority-based thread pool that implements an Aging Algorithm. More...
 
struct  HeavyTask
 A simulated CPU-intensive workload functor. More...
 

Functions

int main ()
 The Main Test Harness for the Aging Priority Pool.
 

Function Documentation

◆ main()

int main ( void  )

The Main Test Harness for the Aging Priority Pool.

  • This demonstration performs the following steps:
  1. Spawns a pool with a single thread to force queueing.
  2. Submits a long-running "Blocking Task" to hold the worker.
  3. Submits a "Starved" low-priority task.
  4. Floods the queue with "Medium" priority tasks.
  5. Observes the aging monitor as it boosts the starved task ahead of the flood.
  • Returns
    int Execution status code.

Definition at line 198 of file AgingPriority.cpp.

198 {
199 // We use ONLY 1 thread so that every task after the first one
200 // MUST wait in the heap, allowing us to observe the aging process.
201 AgingPriorityPool pool(1);
202
203 std::cout << "--- STARTING AGING DEMONSTRATION ---\n";
204
205 // Step 1: Block the worker for 4 seconds
206 std::cout << "Step 1: Submitting 'BLOCKING_TASK' (Prio: 100)...\n";
207 pool.enqueue(100, "BLOCKING_TASK", HeavyTask{4000});
208
209 // Step 2: Add a task that would normally wait forever (Starvation)
210 std::cout << "Step 2: Submitting 'STARVED_REWARD_TASK' (Prio: 20)...\n";
211 pool.enqueue(20, "STARVED_REWARD_TASK", HeavyTask{500});
212
213 // Step 3: Flood the system with medium tasks (Prio: 50)
214 std::cout << "Step 3: Flooding queue with 20 'MEDIUM_TASKS' (Prio: 50)...\n";
215 for(int i = 1; i <= 20; ++i) {
216 pool.enqueue(50, "MEDIUM_TASK_" + std::to_string(i), HeavyTask{1000});
217 }
218
219 std::cout << "\n--- OBSERVATION PERIOD ---\n";
220 std::cout << "The 'STARVED' task starts at Priority 20.\n";
221 std::cout << "Every 2 seconds, it gains +20 priority.\n";
222 std::cout << "Wait ~4 seconds: It becomes Priority 60 and jumps ahead of all Medium Tasks!\n\n";
223
224 // Keep the main thread alive to watch the console logs as workers process the aged tasks
225 std::this_thread::sleep_for(std::chrono::seconds(20));
226
227 return 0;
228}
A priority-based thread pool that implements an Aging Algorithm.
A simulated CPU-intensive workload functor.

References AgingPriorityPool::enqueue().

Here is the call graph for this function: