Skip to main content

actix_rt/
lib.rs

1//! Tokio-based single-threaded async runtime for the Actix ecosystem.
2//!
3//! In most parts of the the Actix ecosystem, it has been chosen to use !Send futures. For this
4//! reason, a single-threaded runtime is appropriate since it is guaranteed that futures will not
5//! be moved between threads. This can result in small performance improvements over cases where
6//! atomics would otherwise be needed.
7//!
8//! To achieve similar performance to multi-threaded, work-stealing runtimes, applications
9//! using `actix-rt` will create multiple, mostly disconnected, single-threaded runtimes.
10//! This approach has good performance characteristics for workloads where the majority of tasks
11//! have similar runtime expense.
12//!
13//! The disadvantage is that idle threads will not steal work from very busy, stuck or otherwise
14//! backlogged threads. Tasks that are disproportionately expensive should be offloaded to the
15//! blocking task thread-pool using [`task::spawn_blocking`].
16//!
17//! # Examples
18//! ```no_run
19//! use std::sync::mpsc;
20//! use actix_rt::{Arbiter, System};
21//!
22//! let _ = System::new();
23//!
24//! let (tx, rx) = mpsc::channel::<u32>();
25//!
26//! let arbiter = Arbiter::new();
27//! arbiter.spawn_fn(move || tx.send(42).unwrap());
28//!
29//! let num = rx.recv().unwrap();
30//! assert_eq!(num, 42);
31//!
32//! arbiter.stop();
33//! arbiter.join().unwrap();
34//! ```
35//!
36#![allow(clippy::type_complexity)]
37#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
38#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
39
40use std::future::Future;
41
42// Cannot define a main macro when compiled into test harness.
43// Workaround for https://github.com/rust-lang/rust/issues/62127.
44#[cfg(all(feature = "macros", not(test)))]
45pub use actix_macros::main;
46#[cfg(feature = "macros")]
47pub use actix_macros::test;
48
49mod arbiter;
50mod runtime;
51mod system;
52
53#[deprecated(since = "2.11.0", note = "Prefer `std::pin::pin!`.")]
54pub use tokio::pin;
55use tokio::task::JoinHandle;
56
57pub use self::{
58    arbiter::{Arbiter, ArbiterHandle},
59    runtime::Runtime,
60    system::{System, SystemRunner, SystemStop},
61};
62
63pub mod signal {
64    //! Asynchronous signal handling (Tokio re-exports).
65
66    #[cfg(unix)]
67    pub mod unix {
68        //! Unix specific signals (Tokio re-exports).
69        pub use tokio::signal::unix::*;
70    }
71    pub use tokio::signal::ctrl_c;
72}
73
74pub mod net {
75    //! TCP/UDP/Unix bindings (mostly Tokio re-exports).
76
77    use std::{
78        future::Future,
79        io,
80        pin::pin,
81        task::{Context, Poll},
82    };
83
84    use tokio::io::{AsyncRead, AsyncWrite, BufReader, Interest};
85    #[cfg(unix)]
86    pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
87    pub use tokio::{
88        io::Ready,
89        net::{TcpListener, TcpSocket, TcpStream, UdpSocket},
90    };
91
92    /// Extension trait over async read+write types that can also signal readiness.
93    #[doc(hidden)]
94    pub trait ActixStream: AsyncRead + AsyncWrite + Unpin {
95        /// Poll stream and check read readiness of Self.
96        ///
97        /// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
98        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
99
100        /// Poll stream and check write readiness of Self.
101        ///
102        /// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
103        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
104    }
105
106    impl ActixStream for TcpStream {
107        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
108            let ready = self.ready(Interest::READABLE);
109            pin!(ready).poll(cx)
110        }
111
112        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
113            let ready = self.ready(Interest::WRITABLE);
114            pin!(ready).poll(cx)
115        }
116    }
117
118    #[cfg(unix)]
119    impl ActixStream for UnixStream {
120        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
121            let ready = self.ready(Interest::READABLE);
122            pin!(ready).poll(cx)
123        }
124
125        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
126            let ready = self.ready(Interest::WRITABLE);
127            pin!(ready).poll(cx)
128        }
129    }
130
131    impl<Io: ActixStream + ?Sized> ActixStream for Box<Io> {
132        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
133            (**self).poll_read_ready(cx)
134        }
135
136        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
137            (**self).poll_write_ready(cx)
138        }
139    }
140
141    impl<Io: ActixStream> ActixStream for BufReader<Io> {
142        fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
143            self.get_ref().poll_read_ready(cx)
144        }
145
146        fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
147            self.get_ref().poll_write_ready(cx)
148        }
149    }
150}
151
152pub mod time {
153    //! Utilities for tracking time (Tokio re-exports).
154
155    pub use tokio::time::{
156        interval, interval_at, sleep, sleep_until, timeout, Instant, Interval, Sleep, Timeout,
157    };
158}
159
160pub mod task {
161    //! Task management (Tokio re-exports).
162
163    pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle};
164}
165
166/// Spawns a future on the current thread as a new task.
167///
168/// If not immediately awaited, the task can be cancelled using [`JoinHandle::abort`].
169///
170/// The provided future is spawned as a new task; therefore, panics are caught.
171///
172/// # Panics
173/// Panics if Actix system is not running.
174///
175/// # Examples
176/// ```
177/// # use std::time::Duration;
178/// # actix_rt::Runtime::new().unwrap().block_on(async {
179/// // task resolves successfully
180/// assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1);
181///
182/// // task panics
183/// assert!(actix_rt::spawn(async {
184///     panic!("panic is caught at task boundary");
185/// })
186/// .await
187/// .unwrap_err()
188/// .is_panic());
189///
190/// // task is cancelled before completion
191/// let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100)));
192/// handle.abort();
193/// assert!(handle.await.unwrap_err().is_cancelled());
194/// # });
195/// ```
196#[track_caller]
197#[inline]
198pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output>
199where
200    Fut: Future + 'static,
201    Fut::Output: 'static,
202{
203    tokio::task::spawn_local(f)
204}