我有一个基于Tokio运行时的Rust异步服务器。它需要处理一些对延迟敏感的I/O绑定请求和重度CPU绑定请求。
我不想让CPU绑定任务垄断Tokio运行时并使I/O绑定任务饥饿,因此我想将CPU绑定任务卸载到专用的、隔离的线程池中(这里关键是隔离,因此在共享线程池上的spawn_blocking/block_in_place是不够的)。如何在Tokio中创建这样一个线程池?
启动两个运行时的天真方法会遇到错误:
thread 'tokio-runtime-worker' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like
block_on
) attempted to block the current thread while the thread is being used to drive asynchronous tasks.'
use tokio; // 0.2.20
fn main() {
let mut main_runtime = tokio::runtime::Runtime::new().unwrap();
let cpu_pool = tokio::runtime::Builder::new().threaded_scheduler().build().unwrap();
let cpu_pool = cpu_pool.handle().clone(); // this is the fix/workaround!
main_runtime.block_on(main_runtime.spawn(async move {
cpu_pool.spawn(async {}).await
}))
.unwrap().unwrap();
}
Tokio是否可以允许两个独立的运行时?创建Tokio中一个隔离的CPU池有更好的方法吗?
block_in_place
,但它没有我所寻求的隔离保证。 - Kornel