Search code examples
rustrust-tokio

Rust Tokio recv() broadcast only once


I can't receive all messages but just one. When I use 2 asynchronous Tokio tasks, the first one only sends values, and the second only receive values.

What might be the problem?

    let (tx, mut rx) = broadcast::channel(1); // broadcast
    let handle = tokio::spawn(async move {
    
        let mut value = 10;
        loop{
            value += 10;            
            tx.send(valu).unwrap();
            thread::sleep(Duration::from_secs(1));
            if(value >= 100){
                break;
            }
        }        
    });
    
    let handle1 = tokio::spawn(async move{
        loop {
       
            // first message recv and stuck
            let _result = rx.recv().await;      
            match _result {
                Ok(value)=>{                        
                    println!("=====> : {}", value);
                },
                Err(e)=>{
                    println!("err : {}", e );
                    break;
                }                
            }                     
        }
    });

Solution

  • Never, ever, use std::thread::sleep() in async code. It blocks.

    If you use tokio::time::sleep(), it works:

    let (tx, mut rx) = broadcast::channel(1); // broadcast
    let handle = tokio::spawn(async move {
        let mut value = 10;
        loop {
            value += 10;
            tx.send(valu).unwrap();
            tokio::time::sleep(Duration::from_seconds(1)).await;
            if value >= 100 {
                break;
            }
        }
    });
    
    let handle1 = tokio::spawn(async move {
        loop {
            let _result = rx.recv().await;
            match _result {
                Ok(value) => {
                    println!("=====> : {}", value);
                }
                Err(e) => {
                    println!("err : {}", e);
                    break;
                }
            }
        }
    });