跳到主要内容

Builder

搜索

结构体 Builder 

Source
pub struct Builder { /* private fields */ }
展开描述

使用自定义配置值构建 Tokio Runtime。

方法 可以链接调用 以设置配置值。 Runtime 通过调用 build 构造。

通过 Builder::new_multi_threadBuilder::new_current_thread 获取新的 Builder 实例。

有关各种配置设置的详细信息,请参阅函数级文档。

§示例

use tokio::runtime::Builder;

fn main() {
    // build runtime
    let runtime = Builder::new_multi_thread()
        .worker_threads(4)
        .thread_name("my-custom-name")
        .thread_stack_size(3 * 1024 * 1024)
        .build()
        .unwrap();

    // use runtime ...
}

实现§

Source§

impl Builder

Source

pub fn new_current_thread() -> Builder

返回一个选定了当前线程调度器的新 builder。

配置方法可以在返回值上链式调用。

要在生成的运行时上派生非 Send 任务,请将其与 LocalSet 结合使用,或调用 build_local 创建 LocalRuntime

Source

pub fn new_multi_thread() -> Builder

返回一个选定了多线程调度器的新 builder。

配置方法可以在返回值上链式调用。

Source

pub fn enable_all(&mut self) -> &mut Self

同时启用 I/O 和 time driver。

这是分别调用 enable_ioenable_time 的简写。如果将来向 Tokio 添加额外的组件,enable_all 将包含这些未来的组件。

§示例
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_all()
    .build()
    .unwrap();
Source

pub fn worker_threads(&mut self, val: usize) -> &mut Self

设置 Runtime 将使用的工作线程数。

这可以是大于 0 的任何数字,但建议将此值保持在较小的范围内。

这将覆盖从环境变量 TOKIO_WORKER_THREADS 读取的值。

§Default

默认值是系统可用的核心数。

当使用 current_thread 运行时,此方法无效。

§示例
§Multi threaded runtime with 4 threads
use tokio::runtime;

// This will spawn a work-stealing runtime with 4 worker threads.
let rt = runtime::Builder::new_multi_thread()
    .worker_threads(4)
    .build()
    .unwrap();

rt.spawn(async move {});
§Current thread runtime (will only run on the current thread via Runtime::block_on)
use tokio::runtime;

// Create a runtime that _must_ be driven from a call
// to `Runtime::block_on`.
let rt = runtime::Builder::new_current_thread()
    .build()
    .unwrap();

// This will run the runtime and future on the current thread
rt.block_on(async move {});
§Panics

如果 val 不大于 0,则会发生 panic。

Source

pub fn max_blocking_threads(&mut self, val: usize) -> &mut Self

指定 Runtime 派生的额外线程的上限。

这些线程用于阻塞操作,例如通过 spawn_blocking 派生的任务,包括但不限于:

worker_threads 不同,它们并不总是处于活动状态,如果空闲时间过长就会退出。你可以使用 thread_keep_alive 更改此超时时长。

建议不要将此上限设置得过低,以避免需要 spawn_blocking 的操作挂起。

默认值为 512。

§Queue Behavior

当提交阻塞任务时,它将被插入到队列中。如果有可用的空闲线程,会通知其中一个线程运行该任务。否则,如果尚未达到此方法设置的阈值,则会派生一个新线程。如果没有可用的空闲线程且不允许再派生线程,则该任务将保留在队列中,直到某个繁忙的线程拾取它。请注意,由于队列不应用任何背压,它可能会无限增长。

§Panics

如果 val 不大于 0,则会发生 panic。

§Upgrading from 0.x

在旧版本中,max_threads 同时限制阻塞线程和 worker 线程,但当前的 max_blocking_threads 不在计数中包含异步 worker 线程。

Source

pub fn thread_name(&mut self, val: impl Into<String>) -> &mut Self

设置由 Runtime 线程池派生的线程的名称。

默认名称为 "tokio-rt-worker"。

§示例

let rt = runtime::Builder::new_multi_thread()
    .thread_name("my-pool")
    .build();
Source

pub fn name(&mut self, val: impl Into<String>) -> &mut Self

设置运行时的名称。

§示例

let rt = runtime::Builder::new_multi_thread()
    .name("my-runtime")
    .build();
§Panics

如果传入空字符串作为参数,此函数将发生 panic。

Source

pub fn thread_name_fn<F>(&mut self, f: F) -> &mut Self
where F: Fn() -> String + Send + Sync + 'static,

设置用于生成由 Runtime 线程池派生的线程名称的函数。

默认的名称函数为 || "tokio-rt-worker".into()

§示例
let rt = runtime::Builder::new_multi_thread()
    .thread_name_fn(|| {
       static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
       let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
       format!("my-pool-{}", id)
    })
    .build();
Source

pub fn thread_stack_size(&mut self, val: usize) -> &mut Self

设置工作线程的栈大小(以字节为单位)。

如果平台指定了最小栈大小,则实际栈大小可能大于此值。

派生线程的默认栈大小为 2 MiB,但该栈大小将来可能会更改。

§示例

let rt = runtime::Builder::new_multi_thread()
    .thread_stack_size(32 * 1024)
    .build();
Source

pub fn on_thread_start<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static,

在每个线程启动之后、开始执行工作之前,执行函数 f

此函数用于簿记和监控用途。

§示例
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_start(|| {
        println!("thread started");
    })
    .build();
Source

pub fn on_thread_stop<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static,

在每个线程停止之前执行函数 f

此函数用于簿记和监控用途。

§示例
{
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_stop(|| {
        println!("thread stopping");
    })
    .build();
Source

pub fn on_thread_park<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static,

在线程即将 park(变为空闲)之前执行函数 ff 在 Tokio 上下文内被调用,因此可以调用诸如 tokio::spawn 之类的函数,并可能导致此线程立即被 unpark。

这可用于仅在执行器空闲时启动工作,或用于簿记和监控目的。

注意:一个运行时只能有一个 park 回调;多次调用此函数将替换最后定义的回调,而不是添加到其中。

§示例
§Multithreaded executor
let once = AtomicBool::new(true);
let barrier = Arc::new(Barrier::new(2));

let runtime = runtime::Builder::new_multi_thread()
    .worker_threads(1)
    .on_thread_park({
        let barrier = barrier.clone();
        move || {
            let barrier = barrier.clone();
            if once.swap(false, Ordering::Relaxed) {
                tokio::spawn(async move { barrier.wait().await; });
           }
        }
    })
    .build()
    .unwrap();

runtime.block_on(async {
   barrier.wait().await;
})
§Current thread executor
let once = AtomicBool::new(true);
let barrier = Arc::new(Barrier::new(2));

let runtime = runtime::Builder::new_current_thread()
    .on_thread_park({
        let barrier = barrier.clone();
        move || {
            let barrier = barrier.clone();
            if once.swap(false, Ordering::Relaxed) {
                tokio::spawn(async move { barrier.wait().await; });
           }
        }
    })
    .build()
    .unwrap();

runtime.block_on(async {
   barrier.wait().await;
})
Source

pub fn on_thread_unpark<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static,

在线程 unpark(开始执行任务)之后立即执行函数 f

这用于簿记和监控用途;请注意,当应用程序允许一个或多个运行时线程空闲时,此回调中的工作会增加延迟。

注意:一个运行时只能有一个 unpark 回调;多次调用此函数将替换最后定义的回调,而不是添加到其中。

§示例
let runtime = runtime::Builder::new_multi_thread()
    .on_thread_unpark(|| {
        println!("thread unparking");
    })
    .build();

runtime.unwrap().block_on(async {
   tokio::task::yield_now().await;
   println!("Hello from Tokio!");
})
Source

pub fn build(&mut self) -> Result<Runtime>

创建已配置的 Runtime

返回的 Runtime 实例已准备好派生任务。

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

let rt  = Builder::new_multi_thread().build().unwrap();

rt.block_on(async {
    println!("Hello from the Tokio runtime");
});
Source

pub fn build_local(&mut self, options: LocalOptions) -> Result<LocalRuntime>

创建已配置的 LocalRuntime

返回的 LocalRuntime 实例已准备好派生任务。

§Panics

如果运行时是通过 new_multi_thread() 配置的,则会发生 panic。

§示例
use tokio::runtime::{Builder, LocalOptions};

let rt = Builder::new_current_thread()
    .build_local(LocalOptions::default())
    .unwrap();

rt.spawn_local(async {
    println!("Hello from the Tokio runtime");
});
Source

pub fn thread_keep_alive(&mut self, duration: Duration) -> &mut Self

为阻塞池中的线程设置自定义超时时间。

默认情况下,线程的超时时间设置为 10 秒。可以使用 .thread_keep_alive() 进行覆盖。

§Example
let rt = runtime::Builder::new_multi_thread()
    .thread_keep_alive(Duration::from_millis(100))
    .build();
Source

pub fn global_queue_interval(&mut self, val: u32) -> &mut Self

设置调度器在 poll 全局任务队列之前的调度器 tick 数。

一个调度器 "tick" 大致对应于对任务的一次 poll 调用。

对于 current-thread 调度器,默认的全局队列间隔为 31。有关多线程调度器的默认行为,请参阅模块文档

调度器有一个本地队列用于存放已认领的任务,以及一个全局队列用于存放新到达的任务。将间隔设置为较小的值会提高调度器的公平性,但代价是更多的同步开销。这有利于优先开始新工作,特别是当任务频繁 yield 而不是完成或等待进一步的 I/O 时。将间隔设置为 1 将优先处理全局队列,并且仅在全局队列为空时才会执行本地队列中的任务。相反,较高的值优先处理现有工作,是大多数任务快速完成 poll 时的不错选择。

§Panics

如果传入 0 作为参数,此函数将发生 panic。

§示例
let rt = runtime::Builder::new_multi_thread()
    .global_queue_interval(31)
    .build();
Source

pub fn event_interval(&mut self, val: u32) -> &mut Self

设置调度器在 poll 外部事件(timer、I/O 等)之前的调度器 tick 数。

一个调度器 "tick" 大致对应于对任务的一次 poll 调用。

默认情况下,所有调度器类型的事件间隔为 61

设置事件间隔决定了传递这些外部事件(可能会唤醒其他任务)的有效"优先级",相对于执行当前已准备好运行的任务。当任务频繁长时间 poll 或不频繁 yield 时,较小的值很有用,因为这样可以避免在处理 I/O 事件时产生过长的延迟。相反,拾取新事件需要额外的同步和系统调用开销,因此如果任务通常很快完成 poll,较高的事件间隔可以最大限度地减少该开销,同时仍保持调度器对事件的响应能力。

§Panics

如果传入 0 作为参数,此函数将发生 panic。

§示例
let rt = runtime::Builder::new_multi_thread()
    .event_interval(31)
    .build();
Source§

impl Builder

Source

pub fn enable_io(&mut self) -> &mut Self

启用 I/O driver。

这将允许在运行时上使用 net、process、signal 以及某些 I/O 类型。

§示例
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_io()
    .build()
    .unwrap();
Source

pub fn max_io_events_per_tick(&mut self, capacity: usize) -> &mut Self

启用 I/O driver 并配置每个 tick 处理的最大事件数。

§示例
use tokio::runtime;

let rt = runtime::Builder::new_current_thread()
    .enable_io()
    .max_io_events_per_tick(1024)
    .build()
    .unwrap();
Source§

impl Builder

Source

pub fn enable_time(&mut self) -> &mut Self

启用 time driver。

这将允许在运行时上使用 tokio::time

§示例
use tokio::runtime;

let rt = runtime::Builder::new_multi_thread()
    .enable_time()
    .build()
    .unwrap();

Trait 实现§

Source§

impl Debug for Builder

Source§

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

使用给定的格式化器格式化此值。 更多信息

自动 Trait 实现§

Blanket 实现§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
Source§

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

Source§

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

Mutably borrows from an owned value. 更多信息
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

原样返回传入的参数。

Source§

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

Source§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换的具体行为取决于 From<T> for U 的实现方式。

Source§

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

Source§

type Error = Infallible

转换出错时返回的类型。
Source§

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

执行转换。
Source§

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

Source§

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

转换出错时返回的类型。
Source§

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

执行转换。