Spec-Zone.ru › Tokio

Struct LocalRuntime

pub struct LocalRuntime { /* private fields */ }
Available on crate feature rt only.

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

pub 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...

pub 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...

pub 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;

// 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");
});

pub 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;

// 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");
});

pub 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");
});

pub 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();
}

pub 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
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));
}

pub 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();
   });
}

pub 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

Formats the value using the given formatter. Read more

impl Drop for LocalRuntime

fn drop(&mut self)

Executes the destructor for this type. Read more

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

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 T
where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more

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

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more

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

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

Mutably borrows from an owned value. Read more

impl<T> From<T> for T

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Instrument for T

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

impl<T, U> Into<U> for T
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 T
where U: Into<T>,

type Error = Infallible

The type returned in the event of a conversion error.

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.

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

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T> WithSubscriber for T

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

MIT License
Copyright © Tokio Contributors
https://docs.rs/tokio/1.53.1/tokio/runtime/struct.LocalRuntime.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API