Skip to content

Commit

Permalink
feature: first try on rust thread
Browse files Browse the repository at this point in the history
  • Loading branch information
tyrchen committed Mar 30, 2024
1 parent e79a802 commit 3a90550
Show file tree
Hide file tree
Showing 3 changed files with 138 additions and 0 deletions.
75 changes: 75 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.81"
rand = "0.8.5"
61 changes: 61 additions & 0 deletions examples/thread1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use anyhow::{anyhow, Result};
use std::{sync::mpsc, thread, time::Duration};

const NUM_PRODUCERS: usize = 4;

#[allow(dead_code)]
#[derive(Debug)]
struct Msg {
idx: usize,
value: usize,
}

fn main() -> Result<()> {
let (tx, rx) = mpsc::channel();

// 创建 producers
for i in 0..NUM_PRODUCERS {
let tx = tx.clone();
thread::spawn(move || producer(i, tx));
}
drop(tx); // 释放 tx,否则 rx 无法结束

// 创建 consumer
let consumer = thread::spawn(move || {
for msg in rx {
println!("consumer: {:?}", msg);
}
println!("consumer exit");
42
});

let secret = consumer
.join()
.map_err(|e| anyhow!("Thread join error: {:?}", e))?;

println!("secret: {}", secret);

Ok(())
}

fn producer(idx: usize, tx: mpsc::Sender<Msg>) -> Result<()> {
loop {
let value = rand::random::<usize>();
tx.send(Msg::new(idx, value))?;
let sleep_time = rand::random::<u8>() as u64 * 10;
thread::sleep(Duration::from_millis(sleep_time));
// random exit the producer
if rand::random::<u8>() % 5 == 0 {
println!("producer {} exit", idx);
break;
}
}
// more things to do
Ok(())
}

impl Msg {
fn new(idx: usize, value: usize) -> Self {
Self { idx, value }
}
}

0 comments on commit 3a90550

Please sign in to comment.