#Two awaits in an async function that needs to be tokio spawned

2 messages · Page 1 of 1 (latest)

crisp lance
#

async fn run_hb(cf: ConFile, ctx: &Context) -> Result<()> {
    let mut hb =
        async_zmq::reply(format!("{}://{}:{}", cf.transport, cf.ip, cf.hb_port).as_str())?
        .with_context(&ctx)
        .bind()?;

    while let Some(msg) = hb.next().await {
        let msg = msg.unwrap();
        hb.send(msg).await;
    }
    Ok(())
}
```I have this lovely async function which just handles a heartbeat. Get a message on the zmq socket, and respond that I am still alive and well. I however have things to communicate on other zmq sockets, so I would love to just stick this as a background task using tokio::spawn. Unfortunately, that produces this error

main.rs(15, 29): future is not Send as this value is used across an await
main.rs(15, 35): hb is later dropped here
main.rs(15, 17): consider moving this into a let binding to create a shorter lived borrow
spawn.rs(163, 21): required by a bound in tokio::spawn
```I can tell that it's something with multiple borrows, but I am lost on how to fix it. If I just do hb.send(msg); (that is, without the await), it compiles, but obviously doesn't do anything useful.

#
error: future cannot be sent between threads safely
   --> src/main.rs:34:18
    |
34  |     tokio::spawn(run_hb(hbcf, &hbctx));
    |                  ^^^^^^^^^^^^^^^^^^^^ future returned by `run_hb` is not `Send`
    |
    = help: within `Reply<std::vec::IntoIter<Message>, Message>`, the trait `Sync` is not implemented for `*mut c_void`
note: future is not `Send` as this value is used across an await
   --> src/main.rs:15:21
    |
15  |         hb.send(msg).await;
    |         --          ^^^^^^ await occurs here, with `hb` maybe used later
    |         |
    |         has type `&Reply<std::vec::IntoIter<Message>, Message>` which is not `Send`
note: `hb` is later dropped here
   --> src/main.rs:15:27
    |
15  |         hb.send(msg).await;
    |                           ^
help: consider moving this into a `let` binding to create a shorter lived borrow
   --> src/main.rs:15:9
    |
15  |         hb.send(msg).await;
    |         ^^^^^^^^^^^^
note: required by a bound in `tokio::spawn`
   --> /home/lak/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.22.0/src/task/spawn.rs:163:21
    |
163 |         T: Future + Send + 'static,
    |                     ^^^^ required by this bound in `tokio::spawn`
```here is the more detailed error from cargo build