[Multithread, mpsc channel] Why does this program never end?

⚓ Rust    📅 2026-01-19    👤 surdeus    👁️ 8      

surdeus

Hi, why does this program never end ?

I create 2 threads based on constant array
Each thread computes an algorithm (trivial here) and if result of algorithm matches expected result, it sends the algorithm name to main().
Main() will print all matching algorithms, ie receives algorithm names.

The problem is that received channel iteration seems to block forever.
Best regards

use std::io;
use std::thread;
use std::sync::mpsc; // thread messaging

fn main() -> io::Result<()>  {
    println!("Hello, Thread_001 !");
    
    // conduit for spawed thread to send to main thread
    let (tx, rx) = mpsc::channel();
  
    // Algorithms
	const ALGORITHMS: [(&str, u32); 2] = [
		("algo_one",1),
		("algo_two",2),
	];

    let expected_result: u32 = 10; // some expected result that one algorithm may find
    
    // Vector of threads
	let mut handles = Vec::new();

    // Creating thread for each Algorithms
	for (name, algorithm) in &ALGORITHMS {
        println!("Creating thread for algo {name}");

        // cloning transmitter for this thread
		let tx_ = tx.clone();
        //let tx_ = tx.to_owned();

        // creating thread
		let handle = 
			thread::spawn( move || // keep the "move" as my thread will own outer variables (ie expected_result)
				{
                    let result = algorithm * 10;
                    println!("algo = {name};\tresult = 0x{:04X}", result);
                    if result == expected_result {
					    tx_.send(name).unwrap(); // send "name" to the conduit
                    }
				}
			);
		
        // push handle into vector of threads
		handles.push(handle);		
	}
	
    // Wait for all spawed threads to finish
    println!("nb of threads : {}", handles.len());
	for handle in handles {
        let _ = handle.join().unwrap();
    }
	
    // Print matching algorithm(s)
	for algo_match in rx.iter() {
        println!("Matching algo : {algo_match}");
        // let _ = rx.recv().unwrap();
    }

    // !!! Never reach here !!!!

	println!("End.");
	Ok(())
}

(Playground)

Output:

Hello, Thread_001 !
Creating thread for algo algo_one
Creating thread for algo algo_two
nb of threads : 2
algo = algo_one;	result = 0x000A
algo = algo_two;	result = 0x0014
Matching algo : algo_one

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.58s
     Running `target/debug/playground`

2 posts - 2 participants

Read full topic

🏷️ Rust_feed