同步/异步可互操作通道

Ten*_*Ten 9 asynchronous synchronous rust

当您希望跨线程发送一系列内容(以线程阻塞方式)时,您可以使用例如crossbeam_channel. 当您希望通过 future 发送一系列事物时(以非线程阻塞、future 阻塞的方式),您可以使用例如tokio::sync::mpsc.

什么东西可以让我从阻塞线程发送并从异步上下文接收?(顺便说一句,我可以想象在某些时候需要相反的情况。)

我需要有界通道,发送时线程阻塞,接收时未来阻塞。

我正在寻找一些有点性能的东西,就像在 中所做的等效操作crossbeam_channel,但唤醒未来而不是线程,能够缓冲一些消息以尽可能避免阻塞。这里针对多消息场景给出的答案看起来有点像这方面的补丁。

Ali*_*yhl 12

自从提出这个问题以来,Tokio 提供的频道已经获得了执行此操作的功能。当您处于非异步代码中时,您可以简单地调用通道上的blocking_send和方法:blocking_recv

let (mut tx, mut rx) = tokio::sync::mpsc::channel(10);

std::thread::spawn(move || {
    // send a value, blocking synchronously
    // this allows async channels to be used in non-async contexts
    tx.blocking_send("testing").unwrap();
});

// receive a value, blocking asynchronously
assert_eq!(rx.recv().await.unwrap(), "testing");
Run Code Online (Sandbox Code Playgroud)


ape*_*lla 4

Future 可以以阻塞方式同步运行。您可以使用futures::exector::block_on来执行此操作,以允许在非异步上下文中发送:

let (mut tx, mut rx) = tokio::sync::mpsc::channel(10);

// send a value, blocking synchronously
// this allows async channels to be used in non-async contexts
futures::executor::block_on(tx.send("testing")).unwrap();

// receive a value, blocking asynchronously
assert_eq!(rx.recv().await.unwrap(), "testing");
Run Code Online (Sandbox Code Playgroud)

使用此代码片段,运行 future 来发送值将阻塞线程,直到 future 完成,类似于标准库通道的工作方式。如果需要,这也可以在接收方使用。