use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io;
pub use crate::join_set::JoinSet;
pub mod coop {
pub use crate::coop::{
BUDGET, Cooperative, Unconstrained, consume_budget, cooperative, has_budget_remaining,
unconstrained,
};
}
pub use crate::rt::task::{AbortHandle, FallibleTask, Id, Join, JoinError, Task};
pub use crate::runtime::{spawn, spawn_blocking, spawn_local};
pub use crate::task_local::{AccessError, LocalKey, TaskLocalFuture};
#[expect(
clippy::expect_used,
reason = "documented under `# Panics`; `try_id` answers `None` instead"
)]
pub fn id() -> Id {
try_id().expect("`nuclei::task::id` called outside a task")
}
pub fn try_id() -> Option<Id> {
crate::rt::task::current_id()
}
pub async fn yield_now() {
YieldNow { yielded: false }.await
}
struct YieldNow {
yielded: bool,
}
impl Future for YieldNow {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.yielded {
return Poll::Ready(());
}
self.yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Builder<'a> {
name: Option<&'a str>,
worker: Option<usize>,
}
std::thread_local! {
static NAMING: core::cell::RefCell<Option<std::sync::Arc<str>>> =
const { core::cell::RefCell::new(None) };
}
pub(crate) fn name_now(id: Id) {
if let Some(name) = NAMING
.try_with(|naming| naming.borrow_mut().take())
.ok()
.flatten()
{
crate::rt::task::names::set(id, &name);
}
}
impl<'a> Builder<'a> {
pub fn new() -> Self {
Self {
name: None,
worker: None,
}
}
pub fn name(self, name: &'a str) -> Self {
Self {
name: Some(name),
..self
}
}
pub fn worker(self, worker: usize) -> Self {
Self {
worker: Some(worker),
..self
}
}
pub fn spawn<F>(self, future: F) -> io::Result<Task<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.named(|| {
let inner = crate::rt::runtime::try_current()?;
crate::rt::runtime::try_spawn(&inner, self.worker, future)
})
}
pub fn spawn_local<F>(self, future: F) -> io::Result<Task<F::Output>>
where
F: Future + 'static,
F::Output: 'static,
{
self.named(|| crate::rt::runtime::try_spawn_local(self.worker, future))
}
pub fn spawn_blocking<F, T>(self, f: F) -> io::Result<Task<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
self.named(|| crate::rt::runtime::try_spawn_blocking(self.worker, f))
}
pub fn spawn_on<F>(
self,
future: F,
handle: &crate::runtime::RuntimeHandle,
) -> io::Result<Task<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.named(|| crate::rt::runtime::try_spawn(handle.inner(), self.worker, future))
}
fn named<T>(self, spawn: impl FnOnce() -> io::Result<Task<T>>) -> io::Result<Task<T>> {
let Some(name) = self.name else {
return spawn();
};
let name: std::sync::Arc<str> = std::sync::Arc::from(name);
let _ = NAMING.try_with(|naming| *naming.borrow_mut() = Some(std::sync::Arc::clone(&name)));
let spawned = spawn();
let waiting = NAMING
.try_with(|naming| naming.borrow_mut().take())
.ok()
.flatten();
if let (Ok(task), Some(name)) = (&spawned, waiting) {
crate::rt::task::names::set(task.id(), &name);
}
spawned
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use super::*;
use crate::rt::task::names;
#[test]
fn names_live_exactly_as_long_as_their_tasks() {
crate::block_on(async {
let done = Builder::new().name("done").spawn(async { 1 }).unwrap();
let id = done.id();
assert_eq!(names::get(id).as_deref(), Some("done"));
assert_eq!(done.await, 1);
let cancelled = Builder::new()
.name("cancelled")
.spawn(core::future::pending::<()>())
.unwrap();
cancelled.abort();
assert!(cancelled.join().await.unwrap_err().is_cancelled());
let blocking = Builder::new()
.name("blocking")
.spawn_blocking(|| 2)
.unwrap();
assert_eq!(blocking.await, 2);
let unnamed = Builder::new().spawn(async { 3 }).unwrap();
assert_eq!(names::get(unnamed.id()), None);
assert_eq!(unnamed.await, 3);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while names::count() != 0 && std::time::Instant::now() < deadline {
yield_now().await;
}
assert_eq!(names::count(), 0, "a destroyed task kept its name");
assert_eq!(names::get(id), None);
});
}
}