Async_std::sync::channel randomly gets stuck on recv

I've been able to reduce the problem to a fairly minimal example below. Basically I have two async tasks that communicate via a channel.

It seems to work properly about 80% of them time. The other 20% of the time, after launching the application, the sending task will run every 1 second, but the receiving task just blocks on recv, never receiving anything.

I'm most likely doing something stupid here.. could anyone please point out my mistake?

async fn f1(ch_in:async_std::sync::Sender<String>) {
    loop {
        println!("here 1");
        ch_in.send("hello".into()).await;
        println!("here 2");
        std::thread::sleep(std::time::Duration::from_millis(1000));
    }
}

async fn f2(ch_out:async_std::sync::Receiver<String>) {
    loop {
        println!("here 3");
        let s = ch_out.recv().await.unwrap();
        println!("here 4");
        println!("{}", s);
    }
}

fn main() {
    let (ch_in, ch_out) = async_std::sync::channel(1000);
    async_std::task::block_on(async {
        async_std::task::spawn(f1(ch_in));
        f2(ch_out).await;
    });
}

You should not use thread::sleep in async code, as it blocks the entire OS thread, preventing other futures from running on it.

1 Like

Use async_std::task::sleep instead

Ahh.. I missed that.
Unfortunately, while that does fix my simple example, my actual code has no sleeping, it blocks on input from a websocket. I'm using async_tungstenite, but I guess I'm not using it properly.

The relevant part:

    let (mut ws, _) = async_tungstenite::async_std::connect_async(uri).await?;
    loop {
        let msg = ws.next().await.ok_or("got none() for ws.next()")??.into_data();
        evch.send(process_msg(msg)).await;
    }

EDIT:
I think I found the problem. :slight_smile: I was calling block_on from within my async code in a place where I should have just been using await.
Thanks for pushing me in the right direction.

1 Like

It’s a bit tough without more code particularly the receive side since it sounds like that is where the error is. A few possibilities:

  • the receive side of your channel isn’t working correctly and your filling up the channel which will block until messages get removed from receive. This doesn’t sound right based on your description though.
  • similarly, the receive panics. I’d recommend not using unwrap on the receive side and instead do proper error handling and print a message in error
  • or there is something else in your receive side code that is blocked on something else
1 Like