use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::num::NonZeroUsize;
use core::ptr::null_mut;
use core::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, AtomicUsize, Ordering};
#[cfg(target_os = "linux")]
use core::sync::atomic::AtomicU32;
#[cfg(target_os = "linux")]
use core::time::Duration;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread::{self, JoinHandle, Thread};
use crossbeam_utils::{Backoff, CachePadded};
use crate::layout::UNITS_PER_WORKER;
const ACTIVE_BITS: u32 = 16;
const ACTIVE_MASK: u64 = (1 << ACTIVE_BITS) - 1;
const GENERATION: u64 = 1 << ACTIVE_BITS;
type Job = *const (dyn Fn(usize) + Sync);
struct Shared {
task: CachePadded<AtomicU64>,
remaining: CachePadded<AtomicUsize>,
job: UnsafeCell<Job>,
caller: UnsafeCell<Option<Thread>>,
panicked: AtomicBool,
busy: AtomicBool,
stop: AtomicBool,
}
unsafe impl Sync for Shared {}
unsafe impl Send for Shared {}
impl Shared {
fn task(&self) -> (u64, usize) {
let word = self.task.load(Ordering::Acquire);
(word & !ACTIVE_MASK, usize::try_from(word & ACTIVE_MASK).unwrap_or(usize::MAX))
}
fn serve(&self, me: usize) {
let mut seen = 0;
loop {
let (generation, active) = self.wait(seen);
if self.stop.load(Ordering::Acquire) {
return;
}
seen = generation;
if me >= active {
continue;
}
let job = unsafe { &**self.job.get() };
if catch_unwind(AssertUnwindSafe(|| job(me))).is_err() {
self.panicked.store(true, Ordering::Release);
}
let caller = unsafe { (*self.caller.get()).clone() };
if self.remaining.fetch_sub(1, Ordering::AcqRel) == 1
&& let Some(caller) = caller
{
caller.unpark();
}
}
}
fn wait(&self, seen: u64) -> (u64, usize) {
let backoff = Backoff::new();
loop {
let task = self.task();
if task.0 != seen || self.stop.load(Ordering::Acquire) {
return task;
}
if backoff.is_completed() {
thread::park();
} else {
backoff.snooze();
}
}
}
}
pub struct Pool {
shared: Arc<Shared>,
workers: Vec<JoinHandle<()>>,
}
impl Pool {
pub fn new(threads: NonZeroUsize) -> Self {
let shared = Arc::new(Shared {
task: CachePadded::new(AtomicU64::new(0)),
remaining: CachePadded::new(AtomicUsize::new(0)),
job: UnsafeCell::new(core::ptr::null::<fn(usize)>() as Job),
caller: UnsafeCell::new(None),
panicked: AtomicBool::new(false),
busy: AtomicBool::new(false),
stop: AtomicBool::new(false),
});
let max = u64::try_from(threads.get()).unwrap_or(ACTIVE_MASK).min(ACTIVE_MASK);
let workers = (1..usize::try_from(max).unwrap_or(1))
.map(|me| {
let shared = shared.clone();
thread::Builder::new().name(format!("paragc-{me}")).spawn(move || shared.serve(me)).expect("起回收线程")
})
.collect();
Self { shared, workers }
}
pub fn threads(&self) -> usize {
self.workers.len() + 1
}
pub fn sized(&self, units: usize) -> usize {
(units / UNITS_PER_WORKER).clamp(1, self.threads())
}
pub fn run<R: Send>(&self, n: usize, f: impl Fn(usize) -> R + Sync) -> Vec<R> {
let n = n.clamp(1, self.threads());
if n == 1 {
return vec![f(0)];
}
let _busy = Busy::enter(&self.shared.busy);
let slots: Vec<UnsafeCell<Option<R>>> = (0..n).map(|_| UnsafeCell::new(None)).collect();
let slots = Slots(&slots);
let job = |me: usize| slots.put(me, f(me));
let job: &(dyn Fn(usize) + Sync) = &job;
let shared = &*self.shared;
#[expect(clippy::transmute_ptr_to_ptr, reason = "要擦掉 dyn 的生命周期,as 转换做不到")]
unsafe {
*shared.job.get() = core::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), Job>(job);
*shared.caller.get() = Some(thread::current());
}
shared.panicked.store(false, Ordering::Relaxed);
shared.remaining.store(n - 1, Ordering::Relaxed);
let active = u64::try_from(n).unwrap_or(ACTIVE_MASK);
let word = shared.task.load(Ordering::Relaxed);
shared.task.store(((word & !ACTIVE_MASK) + GENERATION) | active, Ordering::Release);
for w in &self.workers[..n - 1] {
w.thread().unpark();
}
let mine = catch_unwind(AssertUnwindSafe(|| job(0)));
let backoff = Backoff::new();
while shared.remaining.load(Ordering::Acquire) != 0 {
if backoff.is_completed() {
thread::park();
} else {
backoff.snooze();
}
}
if let Err(e) = mine {
std::panic::resume_unwind(e);
}
assert!(!shared.panicked.load(Ordering::Acquire), "回收线程 panic 了");
slots.take()
}
}
struct Busy<'a>(&'a AtomicBool);
impl<'a> Busy<'a> {
fn enter(flag: &'a AtomicBool) -> Self {
let backoff = Backoff::new();
while flag.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
backoff.snooze();
}
Self(flag)
}
}
impl Drop for Busy<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
struct Slots<'a, R>(&'a [UnsafeCell<Option<R>>]);
unsafe impl<R: Send> Sync for Slots<'_, R> {}
impl<R> Slots<'_, R> {
fn put(&self, me: usize, r: R) {
unsafe { *self.0[me].get() = Some(r) };
}
fn take(&self) -> Vec<R> {
self.0.iter().map(|s| unsafe { (*s.get()).take() }.expect("每个工号都写了结果")).collect()
}
}
impl Drop for Pool {
fn drop(&mut self) {
self.shared.stop.store(true, Ordering::Release);
self.shared.task.fetch_add(GENERATION, Ordering::AcqRel);
for w in self.workers.drain(..) {
w.thread().unpark();
let _ = w.join();
}
}
}
const FIRST: usize = 32;
const SEGMENTS: usize = usize::BITS as usize - FIRST.trailing_zeros() as usize;
struct Cell<T> {
ready: AtomicBool,
value: UnsafeCell<MaybeUninit<T>>,
}
pub struct SegVec<T> {
segments: [AtomicPtr<Cell<T>>; SEGMENTS],
len: AtomicUsize,
}
unsafe impl<T: Send + Sync> Sync for SegVec<T> {}
unsafe impl<T: Send> Send for SegVec<T> {}
impl<T> Default for SegVec<T> {
fn default() -> Self {
Self { segments: core::array::from_fn(|_| AtomicPtr::new(null_mut())), len: AtomicUsize::new(0) }
}
}
impl<T> SegVec<T> {
fn capacity(k: usize) -> usize {
FIRST << k
}
fn locate(i: usize) -> (usize, usize) {
let j = i + FIRST;
let k = (usize::BITS - 1 - j.leading_zeros()) as usize - FIRST.trailing_zeros() as usize;
(k, j - Self::capacity(k))
}
fn segment(&self, k: usize) -> *mut Cell<T> {
let seg = self.segments[k].load(Ordering::Acquire);
if !seg.is_null() {
return seg;
}
let fresh: Box<[Cell<T>]> = (0..Self::capacity(k)).map(|_| Cell { ready: AtomicBool::new(false), value: UnsafeCell::new(MaybeUninit::uninit()) }).collect();
let fresh = Box::into_raw(fresh).cast::<Cell<T>>();
match self.segments[k].compare_exchange(null_mut(), fresh, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => fresh,
Err(won) => {
drop(unsafe { Box::from_raw(core::ptr::slice_from_raw_parts_mut(fresh, Self::capacity(k))) });
won
}
}
}
fn cell(&self, i: usize) -> Option<&Cell<T>> {
let (k, at) = Self::locate(i);
let seg = self.segments.get(k)?.load(Ordering::Acquire);
(!seg.is_null()).then(|| unsafe { &*seg.add(at) })
}
pub fn push(&self, value: T) -> usize {
let i = self.len.fetch_add(1, Ordering::AcqRel);
let (k, at) = Self::locate(i);
let cell = unsafe { &*self.segment(k).add(at) };
unsafe { (*cell.value.get()).write(value) };
cell.ready.store(true, Ordering::Release);
i
}
pub fn len(&self) -> usize {
self.len.load(Ordering::Acquire)
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, i: usize) -> Option<&T> {
let cell = self.cell(i)?;
cell.ready.load(Ordering::Acquire).then(|| unsafe { (*cell.value.get()).assume_init_ref() })
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
(0..self.len()).filter_map(|i| self.get(i))
}
pub fn take(&mut self) -> Vec<T> {
let n = core::mem::replace(self.len.get_mut(), 0);
let mut out = Vec::with_capacity(n);
for i in 0..n {
let (k, at) = Self::locate(i);
let seg = *self.segments[k].get_mut();
let cell = unsafe { &mut *seg.add(at) };
*cell.ready.get_mut() = false;
out.push(unsafe { cell.value.get_mut().assume_init_read() });
}
out
}
}
impl<T> Extend<T> for SegVec<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for v in iter {
self.push(v);
}
}
}
impl<T> Drop for SegVec<T> {
fn drop(&mut self) {
drop(self.take());
for (k, seg) in self.segments.iter_mut().enumerate() {
let p = *seg.get_mut();
if !p.is_null() {
drop(unsafe { Box::from_raw(core::ptr::slice_from_raw_parts_mut(p, Self::capacity(k))) });
}
}
}
}
struct Node<T> {
value: T,
next: *mut Node<T>,
}
pub struct PushList<T> {
head: AtomicPtr<Node<T>>,
}
unsafe impl<T: Send> Sync for PushList<T> {}
unsafe impl<T: Send> Send for PushList<T> {}
impl<T> Default for PushList<T> {
fn default() -> Self {
Self { head: AtomicPtr::new(null_mut()) }
}
}
impl<T> PushList<T> {
pub fn push(&self, value: T) {
let node = Box::into_raw(Box::new(Node { value, next: null_mut() }));
let mut head = self.head.load(Ordering::Acquire);
loop {
unsafe { (*node).next = head };
match self.head.compare_exchange_weak(head, node, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => return,
Err(now) => head = now,
}
}
}
pub fn take(&self) -> Vec<T> {
let mut p = self.head.swap(null_mut(), Ordering::AcqRel);
let mut out = Vec::new();
while !p.is_null() {
let node = unsafe { Box::from_raw(p) };
p = node.next;
out.push(node.value);
}
out
}
}
impl<T> Drop for PushList<T> {
fn drop(&mut self) {
drop(self.take());
}
}
#[cfg(target_os = "linux")]
const STACK_TOP: u64 = u32::MAX as u64;
#[cfg(target_os = "linux")]
const STACK_TAG_SHIFT: u32 = u32::BITS;
#[cfg(target_os = "linux")]
pub struct Stack<'a> {
head: &'a AtomicU64,
}
#[cfg(target_os = "linux")]
impl<'a> Stack<'a> {
pub fn on(head: &'a AtomicU64) -> Self {
Self { head }
}
pub fn push(&self, i: u32, next: &AtomicU32) {
let mut head = self.head.load(Ordering::Acquire);
loop {
next.store((head & STACK_TOP) as u32, Ordering::Relaxed);
let new = ((head >> STACK_TAG_SHIFT).wrapping_add(1) << STACK_TAG_SHIFT) | u64::from(i + 1);
match self.head.compare_exchange_weak(head, new, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => return,
Err(now) => head = now,
}
}
}
pub fn pop<'n>(&self, next_of: impl Fn(u32) -> &'n AtomicU32) -> Option<u32> {
let mut head = self.head.load(Ordering::Acquire);
loop {
let top = (head & STACK_TOP) as u32;
let i = top.checked_sub(1)?;
let next = next_of(i).load(Ordering::Relaxed);
let new = ((head >> STACK_TAG_SHIFT).wrapping_add(1) << STACK_TAG_SHIFT) | u64::from(next);
match self.head.compare_exchange_weak(head, new, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => return Some(i),
Err(now) => head = now,
}
}
}
}
#[cfg(target_os = "linux")]
pub trait FutexWord {
fn wait(&self, expected: u32, timeout: Duration);
fn wake_all(&self);
}
#[cfg(all(target_os = "linux", not(miri)))]
impl FutexWord for AtomicU32 {
fn wait(&self, expected: u32, timeout: Duration) {
let ts = libc::timespec {
tv_sec: libc::time_t::try_from(timeout.as_secs()).unwrap_or(libc::time_t::MAX),
tv_nsec: timeout.subsec_nanos().into(),
};
unsafe { libc::syscall(libc::SYS_futex, self.as_ptr(), libc::FUTEX_WAIT, expected, &raw const ts) };
}
fn wake_all(&self) {
unsafe { libc::syscall(libc::SYS_futex, self.as_ptr(), libc::FUTEX_WAKE, i32::MAX) };
}
}
#[cfg(all(target_os = "linux", miri))]
impl FutexWord for AtomicU32 {
fn wait(&self, _: u32, _: Duration) {
std::thread::yield_now();
}
fn wake_all(&self) {}
}
#[cfg(target_os = "linux")]
pub struct Retry {
round: u32,
seed: std::collections::hash_map::RandomState,
}
#[cfg(target_os = "linux")]
impl Retry {
const BASE: Duration = Duration::from_millis(2);
const MAX: Duration = Duration::from_millis(200);
pub fn new() -> Self {
Self { round: 0, seed: std::collections::hash_map::RandomState::new() }
}
pub fn pause(&mut self) {
let cap = Self::BASE.saturating_mul(1 << self.round.min(16)).min(Self::MAX);
let nanos = u64::try_from(cap.as_nanos()).unwrap_or(u64::MAX).max(1);
let jitter = std::hash::BuildHasher::hash_one(&self.seed, self.round) % nanos;
std::thread::sleep(Duration::from_nanos(jitter));
self.round += 1;
}
}