rust - Closing a Channel, like in Go -
does rust have way of "closing" channel, similar available in go?
the idea iterate on channel (receive continually) until channel indicates not produce more values.
use std::sync::{arc, mutex}; use std::thread; use std::sync::mpsc; fn main() { let data = arc::new(mutex::new(0u32)); let (tx, rx) = mpsc::channel::<u32>(); { let (data, tx) = (data.clone(), tx.clone()); thread::spawn(move || { _ in 0..10 { let mut data = data.lock().unwrap(); *data += 1; tx.send(*data).unwrap(); } // *** how close channel here, signal work done? }); } // *** how can detect closed channel here? pattern matching? _ in 0..10 { let x = rx.recv().unwrap(); println!("{}", x); } }
the channel closed when senders have dropped. in code clone , give 1 each each thread, these drop should when threads end. last sender in main thread, , should drop threads have been spawned: drop(tx)
.
finally, easiest way receive this, after drop(tx)
.
for elt in rx { /* */ }
this loop ends when channel closed.
Comments
Post a Comment