跳到主要内容

LocalRuntime

搜索

结构体 LocalRuntime 

源代码
pub struct LocalRuntime { /* 私有字段 */ }
展开描述

本地 Tokio 运行时。

此运行时能够在不使用 LocalSet 的情况下驱动不是 Send + Sync 的任务,因此支持 spawn_local 而无需 LocalSet 上下文。

此运行时不能在线程之间移动,也不能从不同线程驱动。

此运行时与 LocalSet 不兼容。你不应尝试在 LocalRuntime 内驱动 LocalSet

目前,此运行时支持一种风格,其内部与 current_thread 完全相同,只是与 spawn_local 相关的上述差异除外。

有关如何使用运行时的更多一般信息,请参阅 模块 文档。

实现§

源代码§

impl LocalRuntime

源代码

pub fn new() -> Result<LocalRuntime>

使用默认配置值创建一个新的本地运行时实例。

这将导致调度器、I/O 驱动和时间驱动被初始化。

当需要更复杂的配置时,可以使用 运行时构建器

有关更多详细信息,请参阅模块级文档。

§示例

使用默认配置值创建一个新的 LocalRuntime

use tokio::runtime::LocalRuntime;

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

// Use the runtime...
源代码

pub fn handle(&self) -> &Handle

返回运行时 spawner 的句柄。

返回的句柄可用于派生在此运行时上运行的任务,并且可以克隆以便将 Handle 移到其他线程。

由于该句柄可以发送到其他线程,因此它只能用于生成 Send 的任务。

LocalRuntime 的句柄上调用 Handle::block_on 容易出错。有关更多信息,请参阅 Handle::block_on 的文档。

§示例
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,

在运行时上生成一个任务。

这类似于标准 Runtime 上的 spawn 方法,但即使任务不是线程安全的也能工作。

§示例
use tokio::runtime::LocalRuntime;

// 创建运行时
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,

在专用阻塞线程池中的某个线程上运行所提供的函数。

此函数在另一个线程上运行。

有关更多信息,请参阅非本地运行时中的文档

§示例
use tokio::runtime::LocalRuntime;

// 创建运行时
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

在 Tokio 运行时上运行 future 直到完成。这是运行时的入口点。

有关更多信息,请参阅Runtime 上等价方法的文档

§示例
use tokio::runtime::LocalRuntime;

// 创建运行时
let rt  = LocalRuntime::new().unwrap();

// 执行 future,阻塞当前线程直到完成
rt.block_on(async {
    println!("hello");
});
源代码

pub fn enter(&self) -> EnterGuard<'_>

进入运行时上下文。

这允许你构造在创建时必须有执行器可用的类型,例如 SleepTcpStream。它还允许你调用诸如 tokio::spawn 之类的方法。

如果这是 LocalRuntime 的句柄,并且此函数是从创建运行时的同一线程调用的,那么你也能够调用 tokio::task::spawn_local

§示例
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)

关闭运行时,并最多等待 duration 时间让所有已派生的工作停止。

请注意,如果超时到期,spawn_blocking 任务(且只有 spawn_blocking 任务)可能会被遗留。

有关更多详细信息,请参阅 结构体级文档

§示例
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)

关闭运行时,但不等待任何已派生的工作停止。

如果你想从另一个运行时中 drop 一个运行时,这会很有用。通常情况下,drop 一个运行时会无限期阻塞以等待已派生的阻塞任务完成,而异步上下文通常不允许这样做。通过调用 shutdown_background(),你可以从此类上下文中 drop 该运行时。

但请注意,因为我们不等待任何阻塞任务完成,这可能会导致资源泄漏(即任何阻塞任务仍在运行,直到它们返回。其他任务不会泄漏。

有关更多详细信息,请参阅 结构体级文档

此函数等价于调用 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

返回一个视图,可用于获取运行时性能的相关信息。

trait 实现§

源代码§

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

自动 trait 实现§

blanket 实现§

源代码§

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

源代码§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
源代码§

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

源代码§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
源代码§

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

源代码§

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

Mutably borrows from an owned value. 更多信息
源代码§

impl<T> From<T> for T

源代码§

fn from(t: T) -> T

原样返回参数。

源代码§

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

源代码§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换是 From<T> for U 实现选择执行的操作。

源代码§

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

源代码§

type Error = Infallible

转换出错时返回的类型。
源代码§

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

执行转换。
源代码§

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

源代码§

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

转换出错时返回的类型。
源代码§

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

执行转换。