我有一个设置,我的程序使用std :: thread :: spawn
生成多个线程进行CPU绑定计算。
我需要一个GRPC服务器来处理传入的命令,并且还要流式传输工作线程完成的输出。 我正在使用 tonic
用于GRPC服务器,它只提供了在Tokio未来中的异步实现。
我需要能够从“正常”的标准库线程向Tokio未来发送消息。
我将代码简化为最小值:
use std::thread;
use tokio::sync::mpsc; // 1.9.0
fn main() {
let (tx, mut rx) = mpsc::channel(1);
let tokio_runtime = tokio::runtime::Runtime::new().unwrap();
tokio_runtime.spawn(async move {
// the code below starts the GRPC server in reality, here I'm just demonstrating trying to receive a message
while let Some(v) = rx.recv().await {}
});
let h = thread::spawn(move || {
// do work
tx.send(1).await; //<------ error occurs here since I can't await in a non-async block
});
h.join().unwrap();
}
我的主工作线程如何与由Tokio生成的GRPC服务器通信?
mpsc::channel(1)
这里是一个 Tokio 通道,我看到这个函数必须接受一个大于 0 的缓冲区。 - l3utterflytokio::sync::mpsc
通道,因为在 tokio 运行时中,我需要使用recv().await
,这样它就不会阻塞。 - l3utterflyUnboundedSender.send
不是异步的,也不会阻塞。https://docs.rs/tokio/1.9.0/tokio/sync/mpsc/fn.unbounded_channel.html - Colonel Thirty Two