Search code examples
rustsynchronizationrust-tokiochannel

How can I get an equivalent to sync_channel(0) in `tokio`?


I have a project that needs a lot of IO-bound threads (potentially hundreds) which makes the tokio runtime much more ideal than standard threads.

However, I also need rendezvous channels that block both the Sender and Receiver.

std::sync::mpsc has sync_channel(0), but there's no equivalent in tokio::sync::mpsc. channel(0) will panic.

How can I combine these two things? Will standard channels still work?


Solution

  • Standard library channels are not awaitable, so they'll block the executor. As a quick workaround, you could wrap your channel operations in tokio::task::spawn_blocking(), i.e. replace tx.send(message) with spawn_blocking(|| tx.send(message)).await.

    A better option is to use a library that supports async rendezvous channels, such as flume.