slotpoller 0.2.1

Bounded, lock-free futures collection. Faster than FuturesUnordered and other crates.
Documentation
/*
 * Copyright © 2026 Anand Beh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use std::marker::PhantomData;
use std::sync::Barrier;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;

#[derive(Default)]
pub(super) struct Racer<'r> {
    tasks: Vec<Box<dyn FnOnce() + Send + 'r>>,
    scope: PhantomData<&'r ()>,
}

impl<'r> Racer<'r> {
    pub(super) fn add_task<T>(&mut self, task: T)
    where
        T: FnOnce() + Send + 'r,
    {
        self.tasks.push(Box::new(task));
    }

    pub(super) fn execute(self) {
        // Create N+1 threads, release them at the same time
        let barrier = &Barrier::new(1 + self.tasks.len());
        let fast_flag = &AtomicBool::new(false);
        thread::scope(|scope| {
            for task in self.tasks {
                scope.spawn(move || {
                    barrier.wait();
                    while !fast_flag.load(Ordering::Acquire) {
                        thread::yield_now();
                    }
                    task();
                });
            }
            barrier.wait();
            fast_flag.store(true, Ordering::Release);
        });
    }
}