|
| 1 | +use std::{ |
| 2 | + collections::HashMap, |
| 3 | + future::Future, |
| 4 | + sync::{ |
| 5 | + Arc, |
| 6 | + atomic::{AtomicBool, Ordering}, |
| 7 | + }, |
| 8 | +}; |
| 9 | + |
| 10 | +use log::{error, info, warn}; |
| 11 | +use tokio::task::JoinHandle; |
| 12 | + |
| 13 | +/// @module Scheduler |
| 14 | +/// @description Defines the main `Scheduler` that manages the worker pool, task |
| 15 | +/// queue, and task execution lifecycle. |
| 16 | +use super::Worker::Worker; |
| 17 | +use crate::{ |
| 18 | + queue::StealingQueue, |
| 19 | + scheduler::SchedulerBuilder::Concurrency, |
| 20 | + task::{Priority, Task}, |
| 21 | +}; |
| 22 | + |
| 23 | +/// Manages a pool of worker threads and a work-stealing queue to execute tasks |
| 24 | +/// efficiently. This struct is the public-facing API of the Echo scheduler. |
| 25 | +pub struct Scheduler { |
| 26 | + /// The underlying work-stealing queue shared by all workers. |
| 27 | + Queue:Arc<StealingQueue>, |
| 28 | + /// Handles to the spawned worker threads, allowing for graceful shutdown. |
| 29 | + WorkerHandles:Vec<JoinHandle<()>>, |
| 30 | + /// An atomic flag to signal workers to shut down. |
| 31 | + IsRunning:Arc<AtomicBool>, |
| 32 | +} |
| 33 | + |
| 34 | +impl Scheduler { |
| 35 | + /// Creates and starts a new scheduler with a given configuration. |
| 36 | + /// This is a crate-private function, intended to be called only by the |
| 37 | + /// `SchedulerBuilder`. |
| 38 | + /// |
| 39 | + /// @param NumberOfWorkers - The number of worker threads to spawn. |
| 40 | + /// @param QueueConfigs - Configuration for named queues with concurrency |
| 41 | + /// limits (future use). |
| 42 | + pub(crate) fn Start(NumberOfWorkers:usize, _QueueConfigs:HashMap<String, Concurrency>) -> Self { |
| 43 | + info!("[Scheduler] Starting scheduler with {} worker threads.", NumberOfWorkers); |
| 44 | + let IsRunning = Arc::new(AtomicBool::new(true)); |
| 45 | + let Queue = Arc::new(StealingQueue::New(NumberOfWorkers)); |
| 46 | + |
| 47 | + let mut WorkerHandles = Vec::with_capacity(NumberOfWorkers); |
| 48 | + |
| 49 | + for WorkerId in 0..NumberOfWorkers { |
| 50 | + let WorkerInstance = Worker::New(WorkerId, Queue.clone(), IsRunning.clone()); |
| 51 | + let WorkerHandle = tokio::spawn(async move { |
| 52 | + WorkerInstance.Run().await; |
| 53 | + }); |
| 54 | + WorkerHandles.push(WorkerHandle); |
| 55 | + } |
| 56 | + |
| 57 | + Self { Queue, WorkerHandles, IsRunning } |
| 58 | + } |
| 59 | + |
| 60 | + /// Submits a new task (as a `Future`) to the scheduler's global queue. |
| 61 | + /// The task will be picked up by the next available worker. |
| 62 | + /// |
| 63 | + /// @param FutureInstance - The async block or function to execute. |
| 64 | + /// @param TaskPriority - The priority of the task. |
| 65 | + pub fn Submit<F>(&self, FutureInstance:F, TaskPriority:Priority) |
| 66 | + where |
| 67 | + F: Future<Output = ()> + Send + 'static, { |
| 68 | + let NewTask = Task::New(FutureInstance, TaskPriority); |
| 69 | + self.Queue.Push(NewTask); |
| 70 | + } |
| 71 | + |
| 72 | + /// Asynchronously shuts down the scheduler. |
| 73 | + /// |
| 74 | + /// This signals all worker threads to stop their loops and then waits for |
| 75 | + /// them to complete their current tasks and exit gracefully. |
| 76 | + pub async fn Shutdown(&mut self) { |
| 77 | + if !self.IsRunning.swap(false, Ordering::Relaxed) { |
| 78 | + info!("[Scheduler] Shutdown already initiated."); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + info!("[Scheduler] Shutting down worker threads..."); |
| 83 | + for Handle in self.WorkerHandles.drain(..) { |
| 84 | + if let Err(e) = Handle.await { |
| 85 | + error!("[Scheduler] Error joining worker task during shutdown: {}", e); |
| 86 | + } |
| 87 | + } |
| 88 | + info!("[Scheduler] All workers shut down successfully."); |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +impl Drop for Scheduler { |
| 93 | + /// Ensures that the scheduler is shut down when it goes out of scope, |
| 94 | + /// preventing orphaned worker threads. |
| 95 | + fn drop(&mut self) { |
| 96 | + if self.IsRunning.load(Ordering::Relaxed) { |
| 97 | + // If the scheduler is dropped without an explicit async shutdown, |
| 98 | + // we must signal the workers to stop. We cannot await the handles |
| 99 | + // here, but the threads will eventually terminate. |
| 100 | + warn!("[Scheduler] Scheduler dropped without explicit shutdown. Signaling workers to stop."); |
| 101 | + self.IsRunning.store(false, Ordering::Relaxed); |
| 102 | + } |
| 103 | + } |
| 104 | +} |
0 commit comments