[Solved] Close channel in crossbeam threads

Hello,

I'm discovering threading with crossbeam. But program never finish (i thing sender channel is not closed):

use crossbeam::channel::unbounded;
use crossbeam::thread;

fn main() {
    let (sender, receiver) = unbounded();

    thread::scope(|scope| {
        for i in 0..3 {
            let thread_sender = sender.clone();
            scope.spawn(move |_| {
                thread_sender.send(i).unwrap();
            });
        }

        for received in receiver {
            println!("Got: {}", received);
        }
    })
    .unwrap();

    println!("ok")
}

Output is:

Got: 0
Got: 2
Got: 1

But program never exit ("ok" not printed). I tried to drop channel with thread_sender.drop(); just after use it, but it seems not possible:

   |
12 |                 thread_sender.drop();
   |                               ^^^^ explicit destructor calls not allowed

How to solve this ? Thank's !

The thread_sender should drop automatically when the thread exits, but I think you also need to deal with the original sender. Use drop(sender) -- calling mem::drop which is in the standard prelude.

Thank's for your reply. Where i should make this drop(sender) ? (i tried some places without success)

Drop it after you've spawned the threads, but before you go into the receiver loop, as that's where it will run the channel to completion.

It is working ! Thank's !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.