Skip to content

Commit 851c5d6

Browse files
committed
wx, feat: first try on rust thread
1 parent d15e6d2 commit 851c5d6

File tree

3 files changed

+143
-0
lines changed

3 files changed

+143
-0
lines changed

Cargo.lock

Lines changed: 75 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@ edition = "2021"
66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
77

88
[dependencies]
9+
anyhow = "1.0.86"
10+
rand = "0.8.5"

examples/thread1.rs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)