use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use crate::runtime::ScheduledWork;
use crate::transfer::TransferId;
use tokio::sync::Notify;
#[derive(Debug)]
struct WorkQueue {
pending: VecDeque<ScheduledWork>,
in_flight: usize,
}
impl WorkQueue {
fn new() -> Self {
Self {
pending: VecDeque::new(),
in_flight: 0,
}
}
fn push(&mut self, item: ScheduledWork) {
self.pending.push_back(item);
}
fn pop(&mut self) -> Option<ScheduledWork> {
self.pending.pop_front()
}
fn mark_in_flight(&mut self) {
self.in_flight += 1;
}
fn mark_complete(&mut self) {
self.in_flight = self.in_flight.saturating_sub(1);
}
#[allow(dead_code)] fn pending_count(&self) -> usize {
self.pending.len()
}
#[allow(dead_code)] fn in_flight_count(&self) -> usize {
self.in_flight
}
fn remove_for_transfer(&mut self, id: TransferId) -> usize {
let before = self.pending.len();
self.pending.retain(|work| work.descriptor.id() != id);
before - self.pending.len()
}
}
#[derive(Debug)]
pub(super) struct WorkerPool {
queue: Mutex<WorkQueue>,
work_available: Notify,
shutdown: AtomicBool,
started: AtomicBool,
}
impl WorkerPool {
pub(super) fn new() -> Self {
Self {
queue: Mutex::new(WorkQueue::new()),
work_available: Notify::new(),
shutdown: AtomicBool::new(false),
started: AtomicBool::new(false),
}
}
pub(super) fn push(&self, work: ScheduledWork) {
self.queue.lock().unwrap().push(work);
self.work_available.notify_one();
}
pub(super) async fn next_work(&self) -> Option<ScheduledWork> {
loop {
let notified = self.work_available.notified();
if self.shutdown.load(Ordering::Acquire) {
return None;
}
{
let mut queue = self.queue.lock().unwrap();
if let Some(work) = queue.pop() {
queue.mark_in_flight();
return Some(work);
}
}
notified.await;
}
}
pub(super) fn complete(&self) {
self.queue.lock().unwrap().mark_complete();
self.work_available.notify_one();
}
pub(super) fn shutdown(&self) {
self.shutdown.store(true, Ordering::Release);
self.work_available.notify_waiters();
}
pub(super) fn mark_started(&self) -> bool {
self.started
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
}
pub(super) fn is_started(&self) -> bool {
self.started.load(Ordering::Acquire)
}
#[allow(dead_code)] pub(super) fn pending_count(&self) -> usize {
self.queue.lock().unwrap().pending_count()
}
#[allow(dead_code)] pub(super) fn in_flight_count(&self) -> usize {
self.queue.lock().unwrap().in_flight_count()
}
pub(super) fn remove_for_transfer(&self, id: TransferId) -> usize {
self.queue.lock().unwrap().remove_for_transfer(id)
}
}