Calling a block function from async fn?

Say I have a socket, the recv function of which blocks until the next packet arrives.

How can I call this function from a async fn?

Or more generally how can a block function be wrapped as if it were an async fn?

Is tokio_threadpool::blocking a good choice?

tokio_threadpool is a very bad choice for everything — it's an abandoned crate for an outdated version of tokio.

In tokio you can use tokio::task::spawn_blocking. Tokio's multi-threaded runtime is a threadpool already.

There's also tokio::task::block_in_place that is easier to use, but may not be reliable, as it can still block some unrelated tasks in some cases.

4 Likes

Here is a good article on the various approaches to blocking within aync code: Async: What is blocking? – Alice Ryhl

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.