Process never exits after successfully receiving from MPSC channel

后端 未结 1 1988
遥遥无期
遥遥无期 2021-01-26 17:15

Here\'s the code:

use std::thread;
use std::sync::mpsc;

fn main() {

    //spawn threads 
    let (tx, rx) = mpsc::chann         


        
相关标签:
1条回答
  • 2021-01-26 17:30

    tx in your main thread is not dropped until the end of the main function, and rx will not be closed until all senders have been dropped.

    To fix this, you can manually drop it with drop(tx) after you have started all of your threads:

    use std::thread;
    use std::sync::mpsc;
    
    fn main() {
    
        //spawn threads 
        let (tx, rx) = mpsc::channel();
        for mut i in 0 .. 10 {
            let txc = tx.clone();   //clone from the main sender
            thread::spawn( move || {            
                i += 20;
                println!("Sending: {}", i);
                txc.send(i).unwrap_or_else(|e| {
                    eprintln!("{}", e);
                });
            });
        }
    
        // drop tx manually, to ensure that only senders in spawned threads are still in use
        drop(tx);
    
        for received in rx {
            println!("Received: {}", received);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题