@@ -14,23 +14,50 @@ use std::thread;
1414/// Create a producer thread that sends each element from items into the channel.
1515/// The main thread receives all messages and returns them.
1616pub fn simple_send_recv ( items : Vec < String > ) -> Vec < String > {
17- // TODO: Create channel
18- // TODO: Spawn thread to send each element in items
19- // TODO: In main thread, receive all messages and collect into Vec
17+ // Create channel
18+ let ( tx, rx) = mpsc:: channel :: < String > ( ) ;
19+ // Spawn thread to send each element in items
20+ thread:: spawn ( move || {
21+ for item in items {
22+ tx. send ( item) . unwrap ( ) ;
23+ }
24+ } ) ;
25+ // In main thread, receive all messages and collect into Vec
26+ let result = rx. into_iter ( ) . collect ( ) ;
27+ result
2028 // Hint: When all Senders are dropped, recv() returns Err
21- todo ! ( )
2229}
2330
2431/// Create `n_producers` producer threads, each sending a message in format `"msg from {id}"`.
2532/// Collect all messages, sort them lexicographically, and return.
2633///
2734/// Hint: Use `tx.clone()` to create multiple senders. Note that the original tx must also be dropped.
2835pub fn multi_producer ( n_producers : usize ) -> Vec < String > {
29- // TODO: Create channel
30- // TODO: Clone a sender for each producer
31- // TODO: Remember to drop the original sender, otherwise receiver won't finish
32- // TODO: Collect all messages and sort
33- todo ! ( )
36+ // Create channel
37+ let ( tx, rx) = mpsc:: channel :: < String > ( ) ;
38+ // Clone a sender for each producer
39+ let handles = ( 0 ..n_producers) . map ( |i| {
40+ let tx = tx. clone ( ) ;
41+ thread:: spawn ( move || {
42+ tx. send ( format ! ( "msg from {}" , i) ) . unwrap ( ) ;
43+ } )
44+ } ) . collect :: < Vec < _ > > ( ) ;
45+ for handle in handles {
46+ handle. join ( ) . unwrap ( ) ;
47+ }
48+ // 单线程保证了有序性但不是并发了
49+ // thread::spawn(move || {
50+ // for i in 0..n_producers {
51+ // let tx = tx.clone();
52+ // tx.send(format!("msg from {}",i)).unwrap();
53+ // }});
54+ // Remember to drop the original sender, otherwise receiver won't finish
55+ drop ( tx) ;
56+ // Collect all messages and sort
57+ let mut result = rx. into_iter ( ) . collect :: < Vec < _ > > ( ) ;
58+ // 消除并发的无序性
59+ result. sort ( ) ;
60+ result
3461}
3562
3663#[ cfg( test) ]
0 commit comments