tokio-rs / tokio-core

I/O primitives and event loop for async I/O in Rust
Apache License 2.0
638 stars 115 forks source link

Question: How to create a sync wrapper around a async API #294

Closed flosse closed 6 years ago

flosse commented 6 years ago

Hi, I'm building a modbus library based on tokio. The combination of tokio_core, tokio_proto, tokio_proto and tokio_service leads to a great API :) Now there are situations where it would be great to use this API in a synchronous context. Do you have any idea how to create a wrapper to use the async library synchronously?

Here is a naive non-working approach with a dead-lock: https://play.rust-lang.org/?gist=195cee0a4905811f23c234c5706930cb&version=stable

Here is the question on reddit: https://www.reddit.com/r/rust/comments/7spyob/how_to_create_a_sync_wrapper_around_a_async_api/

alexcrichton commented 6 years ago

Thanks for the report! In general you'll want to use core.run to be the synchronous bridge for this, if you use that instead of wait_future does it work for you?

flosse commented 6 years ago

I see, so I add the Core instance into my wrapper? I'll try it tomorrow.

alexcrichton commented 6 years ago

That's one option, yeah! You can also pass it in optionall as well.

flosse commented 6 years ago

It seems to work :)

Here is my simple wrapper: https://github.com/slowtec/tokio-modbus/blob/a8f380e957618edfd74a62c49f64e4c269f5fb45/src/client.rs#L75