|
| 1 | +use anyhow::{anyhow, Ok, Result}; |
| 2 | +use std::{sync::mpsc, thread, time::Duration}; |
| 3 | + |
| 4 | +const NUM_PRODUCERS: usize = 4; |
| 5 | + |
| 6 | +#[derive(Debug)] |
| 7 | +#[allow(dead_code)] |
| 8 | +struct Msg { |
| 9 | + idx: usize, |
| 10 | + value: usize, |
| 11 | +} |
| 12 | + |
| 13 | +fn main() -> Result<()> { |
| 14 | + let (tx, rx) = mpsc::channel(); |
| 15 | + |
| 16 | + // 创建 producers |
| 17 | + for i in 0..NUM_PRODUCERS { |
| 18 | + let tx = tx.clone(); |
| 19 | + thread::spawn(move || producer(i, tx)); |
| 20 | + } |
| 21 | + |
| 22 | + // 释放 tx 否则 rx 无法结束 |
| 23 | + drop(tx); |
| 24 | + |
| 25 | + // 创建 consumer |
| 26 | + let consumer = thread::spawn(move || { |
| 27 | + for msg in rx { |
| 28 | + println!("consumer {:?}", msg); |
| 29 | + } |
| 30 | + println!("consumer exit"); |
| 31 | + |
| 32 | + 42 |
| 33 | + }); |
| 34 | + |
| 35 | + let secret = consumer |
| 36 | + .join() |
| 37 | + .map_err(|e| anyhow!("Thread join error: {:?}", e))?; |
| 38 | + |
| 39 | + println!("secret = {}", secret); |
| 40 | + |
| 41 | + Ok(()) |
| 42 | +} |
| 43 | + |
| 44 | +fn producer(idx: usize, tx: mpsc::Sender<Msg>) -> Result<()> { |
| 45 | + loop { |
| 46 | + let value = rand::random::<usize>(); |
| 47 | + tx.send(Msg::new(idx, value))?; |
| 48 | + let sleep_time = rand::random::<u8>() as u64 * 10; |
| 49 | + thread::sleep(Duration::from_millis(sleep_time)); |
| 50 | + |
| 51 | + // random exit the producer |
| 52 | + if rand::random::<u8>() % 5 == 0 { |
| 53 | + println!("producer {} exit", idx); |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // more things to do |
| 59 | + Ok(()) |
| 60 | +} |
| 61 | + |
| 62 | +impl Msg { |
| 63 | + fn new(idx: usize, value: usize) -> Self { |
| 64 | + Self { idx, value } |
| 65 | + } |
| 66 | +} |
0 commit comments