ntex_rt/rt/mod.rs
1//! Native single-threaded runtime, task spawning, handles, and clock access.
2//!
3//! This module always uses the native scheduler, regardless of which runtime
4//! backend is selected at the crate root. Its spawning functions and handles
5//! are re-exported at the crate root when neither `tokio` nor `compio` is enabled.
6//! The free spawning functions require an active [`Runtime`], not an active
7//! [`System`](crate::System).
8//!
9//! A [`Driver`] supplies the event loop and interprets the [`PollResult`]
10//! returned by [`Runtime::poll`]. [`Runtime::block_on`] installs the native
11//! runtime while that driver runs, even when Tokio or Compio is selected:
12//!
13//! ```no_run
14//! use ntex_rt::rt;
15//!
16//! # fn example(driver: impl ntex_rt::Driver) {
17//! let runtime = rt::Runtime::new(driver.handle());
18//! runtime.block_on(
19//! async {
20//! let task = rt::spawn(async { std::rc::Rc::new(42) });
21//! assert_eq!(*task.await.unwrap(), 42);
22//! },
23//! &driver,
24//! );
25//! # }
26//! ```
27
28use std::cell::{Cell, RefCell};
29use std::sync::{Arc, atomic::Ordering};
30use std::time::{Duration, Instant};
31use std::{fmt, future::Future, io, marker::PhantomData, panic::Location};
32use std::{future::poll_fn, pin::Pin, rc::Rc, task::Poll};
33
34pub use crate::handle::{JoinHandle, RemoteJoinHandle};
35
36use crate::driver::{Driver, Notify, PollResult};
37use crate::handle::SpawnLocation;
38use crate::metrics::Histogram;
39use crate::remote::{Job, RemoteJoin, Runner};
40use crate::time::Timer;
41
42mod queue;
43pub(crate) mod task;
44pub(crate) mod wake;
45
46use self::queue::RunnableQueue;
47
48/// Error returned by [`crate::spawn_sendable()`] when no task output is available.
49///
50/// Native [`JoinHandle`] and [`RemoteJoinHandle`] futures use a separate error
51/// type; this marker is not the error type of their results.
52#[derive(Debug, Copy, Clone)]
53pub struct JoinError;
54
55impl fmt::Display for JoinError {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 write!(f, "JoinError")
58 }
59}
60
61impl std::error::Error for JoinError {}
62
63/// Returns the start of the current runtime turn.
64///
65/// Tasks polled in the same turn observe the same instant, see
66/// [`Runtime::now`]. Returns [`Instant::now()`] outside of a runtime.
67#[inline]
68pub fn now() -> Instant {
69 Runtime::current_now()
70}
71
72/// Spawns a future on the current native runtime and returns its join handle.
73///
74/// The future and its output need not be `Send`. The current system's
75/// [`TaskCallbacks`](crate::TaskCallbacks) wrap the task. Dropping the handle
76/// detaches it unless [`cancel_on_drop`](JoinHandle::cancel_on_drop) is enabled.
77/// Completion is not guaranteed if the runtime shuts down.
78///
79/// A pending task is cancelled once nothing can wake it: no clone of its
80/// waker is stored and its join handle has been dropped. The runtime then
81/// drops the future on its thread without completing it. For example, a
82/// detached task awaiting [`std::future::pending()`], which discards its
83/// waker, is dropped after its first poll along with everything it owns. A
84/// task that waits must leave its waker with whatever ends the wait. While
85/// the join handle is held, the task stays pending instead. The Tokio and
86/// Compio adapters keep such tasks until the runtime shuts down.
87///
88/// # Panics
89///
90/// Panics if no native runtime is active on the current thread.
91#[track_caller]
92pub fn spawn<F>(fut: F) -> JoinHandle<F::Output>
93where
94 F: Future + 'static,
95{
96 let location = Location::caller();
97 let fut = crate::task::wrap(fut);
98 // SAFETY: The current runtime is owner-local, and the wrapped future is `'static`.
99 Runtime::with_current(|rt| unsafe { rt.spawn_at(fut, location) })
100}
101
102/// Spawns a future on the current thread without a join handle.
103///
104/// The future and its output need not be `Send`. The output is dropped on
105/// completion. Like [`spawn()`], this applies registered task callbacks, but
106/// does not create a join handle. Without a handle, the task is cancelled as
107/// soon as it is pending and no clone of its waker is stored, see [`spawn()`].
108///
109/// # Panics
110///
111/// Panics if no native runtime is active on the current thread.
112#[track_caller]
113pub fn spawn_detached<F>(fut: F)
114where
115 F: Future + 'static,
116{
117 let location = Location::caller();
118 let fut = crate::task::wrap(fut);
119 // SAFETY: The current runtime is owner-local, and the wrapped future is `'static`.
120 Runtime::with_current(|rt| unsafe { rt.spawn_detached_at(fut, location) });
121}
122
123/// Log target of the scheduler, also used by its submodules.
124const LOG_TARGET: &str = module_path!();
125
126// marks a reported self-wake streak
127pub(crate) const REPORTED: u32 = 1 << 31;
128
129/// Self-wake bookkeeping of a task, used on the runtime thread only.
130pub(crate) trait TaskStats: Copy {
131 /// Returns the task's spawn location for diagnostics.
132 fn location(self) -> SpawnLocation;
133 /// Consecutive self-wakes, `REPORTED` marks a reported streak.
134 fn self_wakes(self) -> u32;
135 /// Stores the self-wake count and its `REPORTED` marker.
136 fn set_self_wakes(self, wakes: u32);
137 /// Start of the self-wake streak, milliseconds since the runtime epoch.
138 fn streak_start(self) -> u32;
139 /// Records the streak's start in milliseconds since the runtime epoch.
140 fn set_streak_start(self, start: u32);
141}
142
143scoped_tls::scoped_thread_local!(static CURRENT_RUNTIME: Runtime);
144
145/// Index of a thread that owns a runtime, never reused within the process.
146#[cfg(not(ntex_loom))]
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub(crate) struct ThreadId(std::num::NonZeroU16);
149
150// loom threads share the OS thread, and its thread locals
151#[cfg(ntex_loom)]
152pub(crate) type ThreadId = loom::thread::ThreadId;
153
154/// The last issued thread index.
155#[cfg(not(ntex_loom))]
156static THREAD_INDEX: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0);
157
158#[cfg(not(ntex_loom))]
159thread_local!(static THREAD_ID: Cell<Option<ThreadId>> = const { Cell::new(None) });
160
161/// Returns the index of the current thread, assigning one on first use.
162///
163/// Only threads that own a runtime call this, indexes are limited to
164/// `u16::MAX` per process and the process aborts when they run out.
165#[cfg(not(ntex_loom))]
166#[inline]
167pub(crate) fn current_thread_id() -> ThreadId {
168 /// Assigns a never-reused index on the thread's first use.
169 #[cold]
170 fn initialize(slot: &Cell<Option<ThreadId>>) -> ThreadId {
171 let id = THREAD_INDEX
172 .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
173 .ok()
174 .and_then(|n| std::num::NonZeroU16::new(n + 1))
175 .unwrap_or_else(|| {
176 log::error!(target: LOG_TARGET, "Thread indexes are exhausted, {} runtime-owning threads per process", u16::MAX);
177 std::process::abort()
178 });
179 let id = ThreadId(id);
180 slot.set(Some(id));
181 id
182 }
183
184 THREAD_ID.with(|slot| slot.get().unwrap_or_else(|| initialize(slot)))
185}
186
187/// Returns the index of the current thread without assigning one.
188#[cfg(not(ntex_loom))]
189#[inline]
190pub(crate) fn try_current_thread_id() -> Option<ThreadId> {
191 THREAD_ID.with(Cell::get)
192}
193
194/// Sets the last issued thread index, to test exhaustion.
195#[cfg(all(test, not(ntex_loom)))]
196pub(crate) fn set_thread_index(last: u16) {
197 THREAD_INDEX.store(last, Ordering::Relaxed);
198}
199
200/// Returns the current logical Loom thread's identity.
201#[cfg(ntex_loom)]
202pub(crate) fn current_thread_id() -> ThreadId {
203 loom::thread::current().id()
204}
205
206/// Returns the current logical Loom thread's identity.
207#[cfg(ntex_loom)]
208pub(crate) fn try_current_thread_id() -> Option<ThreadId> {
209 Some(loom::thread::current().id())
210}
211
212#[derive(Debug)]
213/// The native single-threaded task scheduler.
214///
215/// This is a thread-local runtime and cannot be sent to other threads, use
216/// [`Handle`] to spawn tasks from other threads.
217/// It is available even when the crate-level APIs select Tokio or Compio.
218/// A [`Driver`] supplies I/O and drives scheduled tasks through
219/// [`block_on`](Self::block_on).
220///
221/// Dropping the runtime cancels its tasks. If cleanup panics, shutdown finishes
222/// before the panic is resumed. A second cleanup panic, or a cleanup panic
223/// while the runtime is dropped during an existing unwind, aborts the process.
224///
225/// A process can create at most 65,535 runtimes, and at most 65,535 threads can
226/// create one. Neither is reused, and the process aborts when either runs out.
227pub struct Runtime {
228 stop: Cell<bool>,
229 queue: Arc<RunnableQueue>,
230 /// Timer wheel, its timers are expired by [`Runtime::poll`].
231 pub(crate) timer: Rc<Timer>,
232 // tasks are polled and dropped on the thread that created the runtime
233 _not_send: PhantomData<*const ()>,
234}
235
236impl Runtime {
237 /// Creates a runtime with default configuration.
238 ///
239 /// `handle` must wake the driver that will drive this runtime. Creating the
240 /// scheduler does not start an event loop or install it as the current runtime.
241 pub fn new(handle: Box<dyn Notify>) -> Self {
242 Self::builder().build(handle)
243 }
244
245 /// Creates a runtime builder.
246 pub fn builder() -> RuntimeBuilder {
247 RuntimeBuilder::new()
248 }
249
250 /// Creates the owner-thread queue and registers its remote wake endpoint.
251 #[allow(clippy::arc_with_non_send_sync)]
252 fn with_builder(builder: &RuntimeBuilder, handle: Box<dyn Notify>) -> Self {
253 let queue = Arc::new(RunnableQueue::new(builder, handle));
254 wake::register(&queue);
255 Self {
256 stop: Cell::new(false),
257 queue,
258 timer: Timer::new_native(builder.timer_resolution),
259 _not_send: PhantomData,
260 }
261 }
262
263 /// Calls `f` with a reference to the native runtime already active on this thread.
264 ///
265 /// # Panics
266 ///
267 /// Panics if no runtime is active on the current thread.
268 pub fn with_current<T, F: FnOnce(&Self) -> T>(f: F) -> T {
269 /// Reports an operation that requires an active runtime.
270 #[cold]
271 fn not_in_neon_runtime() -> ! {
272 panic!("not in a neon runtime")
273 }
274
275 if CURRENT_RUNTIME.is_set() {
276 CURRENT_RUNTIME.with(f)
277 } else {
278 not_in_neon_runtime()
279 }
280 }
281
282 /// Returns `true` if a native runtime is active on the current thread.
283 #[inline]
284 pub(crate) fn has_current() -> bool {
285 CURRENT_RUNTIME.is_set()
286 }
287
288 /// Returns [`Runtime::now`] of the runtime active on the current thread,
289 /// or [`Instant::now()`] if no runtime is active.
290 pub(crate) fn current_now() -> Instant {
291 if CURRENT_RUNTIME.is_set() {
292 CURRENT_RUNTIME.with(Runtime::now)
293 } else {
294 Instant::now()
295 }
296 }
297
298 #[inline]
299 /// Returns a handle to this runtime.
300 pub fn handle(&self) -> Handle {
301 Handle {
302 queue: self.queue.clone(),
303 }
304 }
305
306 /// Spawns a new asynchronous task, returning a [`JoinHandle`] for it.
307 ///
308 /// Spawning a task enables the task to execute concurrently to other tasks.
309 /// There is no guarantee that a spawned task will execute to completion.
310 /// The future and output need not be `Send`. Unlike [`crate::rt::spawn()`],
311 /// this low-level method does not apply registered task callbacks. A
312 /// pending task that nothing can wake is cancelled, as described there.
313 #[track_caller]
314 pub fn spawn<F: Future + 'static>(&self, future: F) -> JoinHandle<F::Output> {
315 // SAFETY: `Runtime` is thread-confined, and the future owns all captured data.
316 unsafe { self.spawn_at(future, Location::caller()) }
317 }
318
319 /// Spawns a task whose future may borrow non-`'static` data.
320 ///
321 /// Like [`spawn`](Self::spawn), this returns a local [`JoinHandle`] and
322 /// does not apply registered task callbacks.
323 ///
324 /// # Safety
325 ///
326 /// All data borrowed by the future must remain valid until the future is
327 /// completed or destroyed, including on unwind. Any borrowed data in the
328 /// output must remain valid until that output is destroyed, even if its join
329 /// handle outlives this runtime. Requesting cancellation, including through
330 /// [`JoinHandle::cancel_on_drop`], does not wait for destruction and is not
331 /// sufficient to end these obligations. Forgetting a join handle does not
332 /// request cancellation.
333 #[track_caller]
334 pub unsafe fn spawn_unchecked<F: Future>(&self, future: F) -> JoinHandle<F::Output> {
335 // SAFETY: The caller guarantees that borrowed future and output data outlive their use.
336 unsafe { self.spawn_at(future, Location::caller()) }
337 }
338
339 /// Spawns a task, `location` is reported by [`Handle::current_task`].
340 ///
341 /// # Safety
342 ///
343 /// The caller should ensure the captured lifetime is long enough.
344 pub(crate) unsafe fn spawn_at<F: Future>(
345 &self,
346 future: F,
347 location: SpawnLocation,
348 ) -> JoinHandle<F::Output> {
349 // SAFETY: `Runtime` is thread-confined, and the caller guarantees the captured lifetime.
350 unsafe { self.queue.spawn(future, location) }
351 }
352
353 /// Spawns a new asynchronous task without a [`JoinHandle`].
354 ///
355 /// The future and output need not be `Send`. The output is dropped on the
356 /// runtime thread when the task completes. This low-level method does not
357 /// apply registered task callbacks. The task is cancelled as soon as it is
358 /// pending and no clone of its waker is stored, see [`crate::rt::spawn()`].
359 #[track_caller]
360 pub fn spawn_detached<F: Future + 'static>(&self, future: F) {
361 // SAFETY: `Runtime` is thread-confined, and the future owns all captured data.
362 unsafe { self.spawn_detached_at(future, Location::caller()) }
363 }
364
365 /// Spawns a detached task, `location` is reported by
366 /// [`Handle::current_task`].
367 ///
368 /// # Safety
369 ///
370 /// The caller should ensure the captured lifetime is long enough.
371 pub(crate) unsafe fn spawn_detached_at<F: Future>(&self, future: F, location: SpawnLocation) {
372 // SAFETY: `Runtime` is thread-confined, and the caller guarantees the captured lifetime.
373 unsafe { self.queue.spawn_detached::<_, true>(future, location) }
374 }
375
376 /// Marks the runtime as awake.
377 ///
378 /// Drivers call this after returning from a blocking wait, before handling
379 /// events that wake tasks. Tasks scheduled from the runtime thread do not
380 /// notify the driver until [`poll`](Self::poll) finds no more tasks to run,
381 /// the driver must call `poll` before blocking again.
382 ///
383 /// Starts a busy period, see [`busy_duration`](Self::busy_duration).
384 #[inline]
385 pub fn awake(&self) {
386 if self.queue.idle.get() {
387 self.queue.start_busy();
388 }
389 }
390
391 /// Polls the runtime and runs scheduled tasks.
392 ///
393 /// Runs bounded batches of ready tasks and remote submissions. Returns
394 /// [`PollResult::PollAgain`] if work remains, [`PollResult::Pending`] if the
395 /// driver may wait for events, or [`PollResult::Ready`] after the future
396 /// supplied to [`block_on`](Self::block_on) completes.
397 ///
398 /// This does not install the runtime as current; [`block_on`](Self::block_on)
399 /// establishes that context before invoking the driver.
400 pub fn poll(&self) -> PollResult {
401 // a turn starts when the driver wakes up or the previous poll finished,
402 // tasks scheduled from other threads do not end the idle state
403 let start = if self.queue.idle.get() {
404 let start = Instant::now();
405 self.queue.busy.start(start);
406 start
407 } else {
408 self.queue.poll_start.get()
409 };
410
411 let result = if self.stop.get() {
412 PollResult::Ready
413 } else {
414 // expired timers wake their tasks before the batch runs
415 self.timer.run_due();
416 if self.queue.run() {
417 PollResult::PollAgain
418 } else {
419 PollResult::Pending(None)
420 }
421 };
422
423 // a runtime that never idles stays visible, its busy period is read
424 // from its start
425 let now = Instant::now();
426 let result = match result {
427 PollResult::Pending(_) => match self.timer.next_deadline() {
428 Some(deadline) if deadline <= now => PollResult::PollAgain,
429 deadline => PollResult::Pending(deadline.map(|d| d - now)),
430 },
431 result => result,
432 };
433 if result != PollResult::Ready {
434 self.queue.add_poll(result == PollResult::PollAgain);
435 self.queue
436 .poll_histogram
437 .record(now.saturating_duration_since(start));
438 }
439 if result == PollResult::PollAgain {
440 self.queue.set_poll_start(now);
441 self.queue.busy.next_turn(now);
442 } else {
443 self.queue.idle.set(true);
444 self.queue.busy.stop(now);
445 }
446 result
447 }
448
449 /// Runs a bounded batch of ready tasks within the current turn.
450 ///
451 /// Unlike [`poll`](Self::poll), the turn does not end: the runtime stays
452 /// awake, [`now`](Self::now) keeps the turn start and busy time is not
453 /// split. Drivers use it to run tasks between chunks of events, then call
454 /// [`poll`](Self::poll) before blocking. Must be called after
455 /// [`awake`](Self::awake). Does nothing once the runtime is stopped.
456 pub fn run_ready(&self) {
457 debug_assert!(!self.queue.idle.get(), "`run_ready` called while idle");
458 if !self.stop.get() {
459 self.queue.run();
460 }
461 }
462
463 /// Returns the start of the current runtime turn.
464 ///
465 /// While the runtime is busy, returns the time the driver woke up or the
466 /// previous [`poll`](Self::poll) finished, tasks polled in the same turn
467 /// observe the same instant. Returns [`Instant::now()`] while the runtime
468 /// is idle.
469 #[inline]
470 pub fn now(&self) -> Instant {
471 if self.queue.idle.get() {
472 Instant::now()
473 } else {
474 self.queue.poll_start.get()
475 }
476 }
477
478 /// Returns the total time the runtime has been busy.
479 ///
480 /// The runtime is busy from [`awake`](Self::awake) until [`poll`](Self::poll)
481 /// finds no more tasks to run. This includes running tasks and handling
482 /// driver events, and excludes time the driver is blocked waiting for events.
483 /// The value is wall-clock time, not CPU time, and includes the current
484 /// busy period, so it can be read from other threads while a task runs.
485 ///
486 /// Utilization over an interval is the busy duration delta divided by the
487 /// elapsed time of the interval.
488 pub fn busy_duration(&self) -> Duration {
489 self.queue.busy.busy_duration()
490 }
491
492 /// Returns how long the current runtime turn has been running, `None`
493 /// while the runtime is idle.
494 ///
495 /// A turn ends when [`poll`](Self::poll) returns, a long turn means a task
496 /// or a driver event handler keeps the runtime from making progress.
497 pub fn current_turn(&self) -> Option<Duration> {
498 self.queue.busy.current_turn()
499 }
500
501 /// Returns the number of scheduler polls, including polls with no ready tasks.
502 ///
503 /// Calls that immediately return [`PollResult::Ready`] are not counted.
504 pub fn poll_count(&self) -> u64 {
505 self.queue.polls.load(Ordering::Relaxed)
506 }
507
508 /// Returns the number of times [`poll`](Self::poll) returned
509 /// [`PollResult::PollAgain`].
510 ///
511 /// `poll` runs a limited number of tasks, and returns `PollAgain` if
512 /// scheduled tasks remain. The `poll_again_count` delta divided by the
513 /// [`poll_count`](Self::poll_count) delta over an interval is the share of
514 /// polls that left a backlog; a value close to 1 means tasks are scheduled
515 /// faster than the runtime runs them.
516 pub fn poll_again_count(&self) -> u64 {
517 self.queue.polls_again.load(Ordering::Relaxed)
518 }
519
520 /// Returns the number of times a task woke itself while it was polled.
521 ///
522 /// A task that wakes itself, for example with `wake_by_ref()` or a yield,
523 /// is scheduled again without waiting for an event. A steadily growing
524 /// count points to tasks that poll in a loop, see
525 /// [`RuntimeBuilder::self_wake_threshold`].
526 pub fn self_wake_count(&self) -> u64 {
527 self.queue.self_wakes.load(Ordering::Relaxed)
528 }
529
530 /// Returns the histogram of runtime turn durations.
531 ///
532 /// A turn starts when the driver wakes up, see [`awake`](Self::awake), or
533 /// the previous [`poll`](Self::poll) returned [`PollResult::PollAgain`],
534 /// and ends when `poll` returns. It includes driver-event processing and
535 /// tasks run by [`run_ready`](Self::run_ready). Calls returning
536 /// [`PollResult::Ready`] are not recorded. Long turns delay driver events
537 /// and increase scheduling latency.
538 pub fn poll_histogram(&self) -> Histogram {
539 self.queue.poll_histogram.snapshot()
540 }
541
542 /// Runs the provided future.
543 ///
544 /// Blocks the current thread until the future completes.
545 /// The future may borrow local data. Other tasks remain scheduled after
546 /// this call and may be driven by a later call; dropping the runtime cancels
547 /// its unfinished tasks. The supplied future is dropped before returning,
548 /// including if the driver fails or panics.
549 ///
550 /// # Panics
551 ///
552 /// Panics if the driver fails to complete the provided future, or if a runtime
553 /// is already active on the current thread. Nested calls would block the
554 /// running task and its runtime until the inner future completes.
555 #[track_caller]
556 pub fn block_on<F: Future>(&self, future: F, driver: &dyn Driver) -> F::Output {
557 /// Rejects blocking from within an already active runtime.
558 #[cold]
559 #[track_caller]
560 fn nested_block_on() -> ! {
561 panic!("Cannot start a runtime from within a runtime")
562 }
563
564 if CURRENT_RUNTIME.is_set() {
565 nested_block_on()
566 }
567
568 let location = Location::caller();
569 self.stop.set(false);
570 self.queue.set_poll_start(Instant::now());
571
572 CURRENT_RUNTIME.set(self, || {
573 let mut result = None;
574
575 // the task outlives this call if the driver fails or panics, it
576 // reaches the borrowing future only through the slot, which the
577 // guard empties before the borrows end
578 let slot = BlockOnSlot(Rc::new(RefCell::new(Some(Box::pin(async {
579 result = Some(future.await);
580 self.stop.set(true);
581 self.queue.notify();
582 })))));
583 let task = slot.0.clone();
584 // SAFETY: `slot` removes the borrowing future before this scope ends, including on unwind.
585 unsafe {
586 self.spawn_detached_at(
587 poll_fn(move |cx| {
588 let mut fut = task.borrow_mut();
589 if let Some(f) = fut.as_mut()
590 && f.as_mut().poll(cx).is_pending()
591 {
592 return Poll::Pending;
593 }
594 *fut = None;
595 Poll::Ready(())
596 }),
597 location,
598 );
599 }
600
601 ntex_error::set_backtrace_start_alt("src/rt/task.rs", 0);
602 let res = driver.run(self);
603 drop(slot);
604 res.expect("Driver failed");
605 result.expect("Driver failed to poll")
606 })
607 }
608}
609
610/// Drops the [`Runtime::block_on`] future when the call returns or unwinds.
611struct BlockOnSlot<F>(Rc<RefCell<Option<Pin<Box<F>>>>>);
612
613impl<F> Drop for BlockOnSlot<F> {
614 /// Removes the borrowing future before the `block_on` scope ends.
615 fn drop(&mut self) {
616 let fut = self.0.borrow_mut().take();
617 drop(fut);
618 }
619}
620
621impl Drop for Runtime {
622 /// Cancels outstanding tasks with this runtime active during cleanup.
623 fn drop(&mut self) {
624 CURRENT_RUNTIME.set(self, || {
625 self.queue.shutdown();
626 self.timer.shutdown();
627 });
628 }
629}
630
631#[derive(Debug)]
632/// A thread-safe handle used to schedule work on a runtime.
633pub struct Handle {
634 queue: Arc<RunnableQueue>,
635}
636
637impl Handle {
638 /// Returns a handle to the runtime active on the current thread.
639 ///
640 /// # Panics
641 ///
642 /// Panics if no runtime is active on the current thread.
643 pub fn current() -> Handle {
644 Runtime::with_current(Runtime::handle)
645 }
646
647 /// Wakes the runtime's driver.
648 ///
649 /// Returns notification errors to the caller without retrying, unlike
650 /// internal scheduler notifications.
651 pub fn notify(&self) -> io::Result<()> {
652 self.queue.handle.notify()
653 }
654
655 /// Returns the total time the runtime has been busy.
656 ///
657 /// See [`Runtime::busy_duration`]. Always returns `Some`, the return type
658 /// matches the other runtime backends.
659 pub fn busy_duration(&self) -> Option<Duration> {
660 Some(self.queue.busy.busy_duration())
661 }
662
663 /// Returns how long the current runtime turn has been running, `None`
664 /// while the runtime is idle.
665 ///
666 /// See [`Runtime::current_turn`].
667 pub fn current_turn(&self) -> Option<Duration> {
668 self.queue.busy.current_turn()
669 }
670
671 /// Returns the number of scheduler polls, including polls with no ready tasks.
672 ///
673 /// See [`Runtime::poll_count`]. Always returns `Some`.
674 pub fn poll_count(&self) -> Option<u64> {
675 Some(self.queue.polls.load(Ordering::Relaxed))
676 }
677
678 /// Returns the number of runtime polls that left scheduled tasks.
679 ///
680 /// See [`Runtime::poll_again_count`]. Always returns `Some`.
681 pub fn poll_again_count(&self) -> Option<u64> {
682 Some(self.queue.polls_again.load(Ordering::Relaxed))
683 }
684
685 /// Returns the number of times a task woke itself while it was polled.
686 ///
687 /// See [`Runtime::self_wake_count`]. Always returns `Some`.
688 pub fn self_wake_count(&self) -> Option<u64> {
689 Some(self.queue.self_wakes.load(Ordering::Relaxed))
690 }
691
692 /// Returns the spawn location of the task the runtime is polling.
693 ///
694 /// Returns `None` while the runtime is idle, handles driver events or
695 /// between tasks. Can be read from other threads, for example to name the
696 /// task that blocks a stalled runtime.
697 pub fn current_task(&self) -> Option<&'static Location<'static>> {
698 let task = self.queue.current.load(Ordering::Relaxed);
699 // SAFETY: The owner only stores null or a pointer to a `&'static Location`.
700 unsafe { task.as_ref() }
701 }
702
703 /// Returns the histogram of runtime turn durations.
704 ///
705 /// See [`Runtime::poll_histogram`]. Always returns `Some`.
706 pub fn poll_histogram(&self) -> Option<Histogram> {
707 Some(self.queue.poll_histogram.snapshot())
708 }
709
710 /// Spawns a task on the handle's runtime and returns a [`RemoteJoinHandle`].
711 ///
712 /// Spawning a task enables the task to execute concurrently to other tasks.
713 /// There is no guarantee that a spawned task will execute to completion.
714 ///
715 /// Both the future and output must be `Send`, including submissions from the
716 /// runtime's own thread, which use the local fast path. Accepted futures
717 /// are polled and dropped on the runtime thread; the output is transferred
718 /// to the caller through the join handle.
719 ///
720 /// The returned join handle is neither `Send` nor `Sync`; dropping it
721 /// detaches the task. Submissions rejected after shutdown are never polled
722 /// and their futures may be dropped on the submitting thread. This low-level
723 /// method does not apply registered task callbacks. A pending task that
724 /// nothing can wake is cancelled, see [`crate::rt::spawn()`].
725 ///
726 /// ```no_run
727 /// # async fn check(hnd: ntex_rt::rt::Handle) {
728 /// let task = hnd.spawn(async { 42 });
729 /// assert_eq!(task.await.unwrap(), 42);
730 /// # }
731 /// ```
732 #[track_caller]
733 pub fn spawn<F>(&self, future: F) -> RemoteJoinHandle<F::Output>
734 where
735 F: Future + Send + 'static,
736 F::Output: Send + 'static,
737 {
738 let location = Location::caller();
739 if Some(self.queue.id) == try_current_thread_id() {
740 // SAFETY: The identity check establishes owner locality, and the future is `'static`.
741 RemoteJoinHandle::local(unsafe { self.queue.spawn(future, location) })
742 } else {
743 let job = Job::new(future, true);
744 let join = RemoteJoin::new(job.clone());
745 // a rejected submission closes the job on this thread
746 // SAFETY: `Runner` contains a `Send`, `'static` future and output, permitting remote submission.
747 unsafe {
748 self.queue.spawn_detached::<_, false>(Runner(job), location);
749 }
750 RemoteJoinHandle::remote(join)
751 }
752 }
753
754 /// Spawns a new asynchronous task without a join handle.
755 ///
756 /// The output is dropped on the runtime thread when the task completes,
757 /// so it does not have to be `Send`.
758 /// The future must be `Send`, even when submitted on the owner thread.
759 /// Rejected submissions are never polled and their futures may be dropped
760 /// on the submitting thread. Registered task callbacks are not applied.
761 /// The task is cancelled as soon as it is pending and no clone of its waker
762 /// is stored, see [`crate::rt::spawn()`].
763 #[track_caller]
764 pub fn spawn_detached<F>(&self, future: F)
765 where
766 F: Future + Send + 'static,
767 {
768 // SAFETY: The future is `Send` and `'static`, permitting either local or remote submission.
769 unsafe {
770 self.queue
771 .spawn_detached::<_, false>(future, Location::caller());
772 }
773 }
774}
775
776impl Clone for Handle {
777 /// Shares the runtime's queue without creating another runtime.
778 fn clone(&self) -> Self {
779 Self {
780 queue: self.queue.clone(),
781 }
782 }
783}
784
785/// Builder for [`Runtime`].
786#[derive(Debug, Clone)]
787pub struct RuntimeBuilder {
788 event_interval: usize,
789 self_wake_limit: u32,
790 self_wake_time: Duration,
791 timer_resolution: Option<u8>,
792}
793
794impl Default for RuntimeBuilder {
795 /// Uses the default scheduler budgets and self-wake thresholds.
796 fn default() -> Self {
797 Self::new()
798 }
799}
800
801impl RuntimeBuilder {
802 /// Creates a builder with the default scheduler budgets and warning thresholds.
803 pub fn new() -> Self {
804 Self {
805 event_interval: 61,
806 self_wake_limit: 10_000,
807 self_wake_time: Duration::from_secs(1),
808 timer_resolution: None,
809 }
810 }
811
812 /// Sets the local task-poll budget for one [`Runtime::poll`] call.
813 ///
814 /// The driver can process external events between calls. Remote work is
815 /// serviced in separate batches, so this is not a strict limit on all work
816 /// done in one call. The default is 61; zero is treated as one.
817 pub fn event_interval(&mut self, val: usize) -> &mut Self {
818 self.event_interval = val.max(1);
819 self
820 }
821
822 /// Sets the self-wake streak that is reported as a possible busy loop.
823 ///
824 /// A task that wakes itself on every poll, for example a loop around
825 /// `wake_by_ref()` or a yield, never waits for an event. The runtime logs
826 /// a warning with the task spawn location once the task wakes itself
827 /// `count` times in a row and the streak lasts at least `duration`. Each
828 /// streak is reported once. A count of 0 disables the warning and per-task
829 /// streak tracking, but preserves [`Runtime::self_wake_count`].
830 ///
831 /// By default, 10 000 self-wakes over at least 1 second.
832 pub fn self_wake_threshold(&mut self, count: u32, duration: Duration) -> &mut Self {
833 self.self_wake_limit = count.min(!REPORTED);
834 self.self_wake_time = duration;
835 self
836 }
837
838 /// Sets the resolution of the runtime timer wheel, in milliseconds.
839 ///
840 /// The resolution must be a power of two between 1 and 16. By default,
841 /// the wheel uses [`Builder::timer_resolution`](crate::Builder::timer_resolution)
842 /// of the system that is current when the first timer is armed.
843 ///
844 /// # Panics
845 ///
846 /// Panics if `millis` is not a power of two between 1 and 16.
847 pub fn timer_resolution(&mut self, millis: u8) -> &mut Self {
848 assert!(
849 millis.is_power_of_two() && millis <= 16,
850 "timer resolution must be a power of two between 1 and 16 ms, got {millis}"
851 );
852 self.timer_resolution = Some(millis);
853 self
854 }
855
856 /// Creates a native runtime using this configuration and driver notifier.
857 ///
858 /// Does not start an event loop. The notifier must wake the driver used to
859 /// run this runtime.
860 pub fn build(&self, handle: Box<dyn Notify>) -> Runtime {
861 Runtime::with_builder(self, handle)
862 }
863}
864
865#[cfg(test)]
866#[path = "../../tests/rt/task_tests.rs"]
867mod task_tests;
868
869#[cfg(all(test, ntex_loom))]
870#[path = "../../tests/rt/task_loom.rs"]
871mod task_loom;
872
873#[cfg(test)]
874#[path = "../../tests/rt/tests.rs"]
875mod tests;