Struct LocalRuntime

pub struct LocalRuntime { /* private fields */ }

A local Tokio runtime.

This runtime is capable of driving tasks which are not Send + Sync without the use of a LocalSet, and thus supports spawn_local without the need for a LocalSet context.

This runtime cannot be moved between threads or driven from different threads.

This runtime is incompatible with LocalSet. You should not attempt to drive a LocalSet within a LocalRuntime.

Currently, this runtime supports one flavor, which is internally identical to current_thread, save for the aforementioned differences related to spawn_local.

For more general information on how to use runtimes, see the module docs.

Implementations

impl LocalRuntime

fn new() -> Result<LocalRuntime>

Creates a new local runtime instance with default configuration values.

This results in the scheduler, I/O driver, and time driver being initialized.

When a more complex configuration is necessary, the runtime builder may be used.

See module level documentation for more details.

Examples

Creating a new LocalRuntime with default configuration values.

use tokio::runtime::LocalRuntime;

let rt = LocalRuntime::new()
    .unwrap();

// Use the runtime...
fn handle(&self) -> &Handle

Returns a handle to the runtime's spawner.

The returned handle can be used to spawn tasks that run on this runtime, and can be cloned to allow moving the Handle to other threads.

As the handle can be sent to other threads, it can only be used to spawn tasks that are Send.

Calling Handle::block_on on a handle to a LocalRuntime is error-prone. Refer to the documentation of Handle::block_on for more.

Examples

use tokio::runtime::LocalRuntime;

let rt = LocalRuntime::new()
    .unwrap();

let handle = rt.handle();

// Use the handle...
fn spawn_local<F>(&self, future: F) -> JoinHandle<F::Output>
where
    F: Future + 'static,
    F::Output: 'static,

Spawns a task on the runtime.

This is analogous to the spawn method on the standard Runtime, but works even if the task is not thread-safe.

Examples

use tokio::runtime::LocalRuntime;

# fn dox() {
// Create the runtime
let rt = LocalRuntime::new().unwrap();

// Spawn a future onto the runtime
rt.spawn_local(async {
    println!("now running on a worker thread");
});
# }
fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
    F: FnOnce() -> R + Send + 'static,
    R: Send + 'static,

Runs the provided function on a thread from a dedicated blocking thread pool.

This function will be run on another thread.

See the documentation in the non-local runtime for more information.

Examples

use tokio::runtime::LocalRuntime;

# fn dox() {
// Create the runtime
let rt = LocalRuntime::new().unwrap();

// Spawn a blocking function onto the runtime
rt.spawn_blocking(|| {
    println!("now running on a worker thread");
});
# }
fn block_on<F: Future>(&self, future: F) -> F::Output

Runs a future to completion on the Tokio runtime. This is the runtime's entry point.

See the documentation for the equivalent method on Runtime for more information.

Examples

use tokio::runtime::LocalRuntime;

// Create the runtime
let rt  = LocalRuntime::new().unwrap();

// Execute the future, blocking the current thread until completion
rt.block_on(async {
    println!("hello");
});
fn enter(&self) -> EnterGuard<'_>

Enters the runtime context.

This allows you to construct types that must have an executor available on creation such as Sleep or TcpStream. It will also allow you to call methods such as tokio::spawn.

If this is a handle to a LocalRuntime, and this function is being invoked from the same thread that the runtime was created on, you will also be able to call tokio::task::spawn_local.

Example

use tokio::runtime::LocalRuntime;
use tokio::task::JoinHandle;

fn function_that_spawns(msg: String) -> JoinHandle<()> {
    // Had we not used `rt.enter` below, this would panic.
    tokio::spawn(async move {
        println!("{}", msg);
    })
}

fn main() {
    let rt = LocalRuntime::new().unwrap();

    let s = "Hello World!".to_string();

    // By entering the context, we tie `tokio::spawn` to this executor.
    let _guard = rt.enter();
    let handle = function_that_spawns(s);

    // Wait for the task before we end the test.
    rt.block_on(handle).unwrap();
}
fn shutdown_timeout(self, duration: Duration)

Shuts down the runtime, waiting for at most duration for all spawned work to stop.

Note that spawn_blocking tasks, and only spawn_blocking tasks, can get left behind if the timeout expires.

See the struct level documentation for more details.

Examples

# #[cfg(not(target_family = "wasm"))]
# {
use tokio::runtime::LocalRuntime;
use tokio::task;

use std::thread;
use std::time::Duration;

fn main() {
   let runtime = LocalRuntime::new().unwrap();

   runtime.block_on(async move {
       task::spawn_blocking(move || {
           thread::sleep(Duration::from_secs(10_000));
       });
   });

   runtime.shutdown_timeout(Duration::from_millis(100));
}
# }
fn shutdown_background(self)

Shuts down the runtime, without waiting for any spawned work to stop.

This can be useful if you want to drop a runtime from within another runtime. Normally, dropping a runtime will block indefinitely for spawned blocking tasks to complete, which would normally not be permitted within an asynchronous context. By calling shutdown_background(), you can drop the runtime from such a context.

Note however, that because we do not wait for any blocking tasks to complete, this may result in a resource leak (in that any blocking tasks are still running until they return. No other tasks will leak.

See the struct level documentation for more details.

This function is equivalent to calling shutdown_timeout(Duration::from_nanos(0)).

use tokio::runtime::LocalRuntime;

fn main() {
   let runtime = LocalRuntime::new().unwrap();

   runtime.block_on(async move {
       let inner_runtime = LocalRuntime::new().unwrap();
       // ...
       inner_runtime.shutdown_background();
   });
}
fn metrics(&self) -> RuntimeMetrics

Returns a view that lets you get information about how the runtime is performing.

Trait Implementations

impl Debug for LocalRuntime

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl Drop for LocalRuntime

fn drop(&mut self)

impl RefUnwindSafe for LocalRuntime

impl UnwindSafe for LocalRuntime

Auto Trait Implementations

impl !Freeze for LocalRuntime

impl !Send for LocalRuntime

impl !Sync for LocalRuntime

impl Unpin for LocalRuntime

impl UnsafeUnpin for LocalRuntime

Blanket Implementations

impl<T> Any for LocalRuntime where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for LocalRuntime where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for LocalRuntime where T: ?Sized,

fn borrow_mut(&mut self) -> &mut T

impl<T> From<T> for LocalRuntime

fn from(t: T) -> T

Returns the argument unchanged.

impl<T, U> Into<U> for LocalRuntime where U: From<T>,

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom<U> for LocalRuntime where U: Into<T>,

type Error = never;
fn try_from(value: U) -> Result<T, never>

impl<T, U> TryInto<U> for LocalRuntime where U: TryFrom<T>,

type Error = <U as TryFrom<T>>::Error;
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>