use core::ffi::c_void;
use core::sync::atomic::{AtomicU32, Ordering};
use crate::sys;
use crate::{ErrorKind, Result};
const DEFAULT_STACK_SIZE: usize = 2 << 20;
const STARTED: u32 = 1;
const DONE: u32 = 2;
struct Start<'a> {
f: fn(usize),
arg: usize,
name: Option<&'a str>,
id: AtomicU32,
id_high: AtomicU32,
started: AtomicU32,
}
pub(crate) unsafe fn thread_main(start: *mut c_void) {
let (f, arg) = {
let start = unsafe { &*start.cast_const().cast::<Start<'_>>() };
if let Some(name) = start.name {
let _ = crate::thread::set_name(name);
}
let id = crate::thread::id();
start.id.store(id as u32, Ordering::Relaxed);
start.id_high.store((id >> 32) as u32, Ordering::Relaxed);
let call = (start.f, start.arg);
start.started.store(STARTED, Ordering::Release);
sys::sync::wake(&start.started, true);
start.started.store(DONE, Ordering::Release);
call
};
f(arg);
}
#[derive(Clone, Debug, Default)]
#[must_use]
pub struct Builder<'a> {
stack_size: usize,
name: Option<&'a str>,
}
impl<'a> Builder<'a> {
#[inline]
pub const fn new() -> Self {
Self {
stack_size: 0,
name: None,
}
}
#[inline]
pub const fn stack_size(mut self, size: usize) -> Self {
self.stack_size = size;
self
}
#[inline]
pub const fn name(mut self, name: &'a str) -> Self {
self.name = Some(name);
self
}
pub fn spawn_fn(self, f: fn(usize), arg: usize) -> Result<Thread> {
if self.name.is_some_and(|name| name.as_bytes().contains(&0)) {
return Err(ErrorKind::InvalidInput.into());
}
let stack_size = match self.stack_size {
0 => DEFAULT_STACK_SIZE,
size => size,
};
let start = Start {
f,
arg,
name: self.name,
id: AtomicU32::new(0),
id_high: AtomicU32::new(0),
started: AtomicU32::new(0),
};
let imp = unsafe { sys::thread::spawn(stack_size, (&raw const start).cast_mut().cast()) }?;
while start.started.load(Ordering::Acquire) == 0 {
let _ = sys::sync::wait(&start.started, 0, None);
}
while start.started.load(Ordering::Acquire) != DONE {
sys::thread::yield_now();
}
let id = u64::from(start.id.load(Ordering::Relaxed))
| u64::from(start.id_high.load(Ordering::Relaxed)) << 32;
Ok(Thread { imp, id })
}
#[cfg(feature = "alloc")]
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
use alloc::boxed::Box;
use alloc::sync::Arc;
fn run<F: FnOnce()>(main: usize) {
let main = unsafe { Box::from_raw(main as *mut F) };
main();
}
fn runner<F: FnOnce()>(_: &F) -> fn(usize) {
run::<F>
}
let packet = Arc::new(Packet(core::cell::UnsafeCell::new(None)));
let theirs = packet.clone();
let main = move || {
let value = f();
unsafe { *theirs.0.get() = Some(value) };
};
let run = runner(&main);
let main = Box::into_raw(Box::new(main));
match self.spawn_fn(run, main as usize) {
Ok(thread) => Ok(JoinHandle { thread, packet }),
Err(error) => {
drop(unsafe { Box::from_raw(main) });
Err(error)
}
}
}
}
pub fn spawn_fn(f: fn(usize), arg: usize) -> Result<Thread> {
Builder::new().spawn_fn(f, arg)
}
#[cfg(feature = "alloc")]
pub fn spawn<F, T>(f: F) -> Result<JoinHandle<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
Builder::new().spawn(f)
}
#[derive(Debug)]
pub struct Thread {
imp: sys::thread::Thread,
id: u64,
}
impl Thread {
#[inline]
#[must_use]
pub fn id(&self) -> u64 {
self.id
}
pub fn join(self) -> Result<()> {
self.imp.join()
}
#[inline]
pub fn detach(self) {}
}
#[cfg(feature = "alloc")]
struct Packet<T>(core::cell::UnsafeCell<Option<T>>);
#[cfg(feature = "alloc")]
unsafe impl<T: Send> Sync for Packet<T> {}
#[cfg(feature = "alloc")]
pub struct JoinHandle<T> {
thread: Thread,
packet: alloc::sync::Arc<Packet<T>>,
}
#[cfg(feature = "alloc")]
impl<T> JoinHandle<T> {
#[inline]
#[must_use]
pub fn id(&self) -> u64 {
self.thread.id
}
pub fn join(self) -> Result<T> {
self.thread.join()?;
let value = unsafe { (*self.packet.0.get()).take() };
value.ok_or_else(|| ErrorKind::Other.into())
}
#[inline]
pub fn detach(self) {}
}
#[cfg(feature = "alloc")]
impl<T> core::fmt::Debug for JoinHandle<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("JoinHandle")
.field("thread", &self.thread)
.finish_non_exhaustive()
}
}