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
luffy2025 committed Nov 23, 2024
1 parent 8a14e8e commit b48d3b8
Show file tree
Hide file tree
Showing 4 changed files with 199 additions and 6 deletions.
8 changes: 2 additions & 6 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,8 @@ All notable changes to this project will be documented in this file. See [conven
---
## [unreleased]

### Miscellaneous Chores
### Features

- initialize basic structure for the repo - ([2436bec](https://github.com/tyrchen/qdrant-lib/commit/2436bec4a02caac64f6c1f97ca79b6ce745b4f53)) - Tyr Chen

### Other

- init the project and add the assets - ([6a3ca0a](https://github.com/tyrchen/qdrant-lib/commit/6a3ca0a900451c55969cc8dec20afb5351d86599)) - Tyr Chen
- initial project - ([8a14e8e](https://github.com/luffy2025/r-concurrency/commit/8a14e8ea7a8257393d41556fcad2ec6373caa396)) - Luffy2025

<!-- generated by git-cliff -->
140 changes: 140 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.93"
rand = "0.8.5"
55 changes: 55 additions & 0 deletions examples/thread1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use anyhow::Result;
use std::time::Duration;
use std::{sync::mpsc, thread};

const N: usize = 4;

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

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

fn main() -> Result<()> {
let (tx, rx) = mpsc::channel();
for i in 0..N {
let tx = tx.clone();
thread::spawn(move || producer(i, tx));
}
drop(tx); // 线程中的tx都是由clone创建的,这里drop掉初始的tx。

let consumer = thread::spawn(move || {
for msg in rx {
println!("msg: {:?}", msg);
}
println!("consumer exit");
42 // consumer闭包可以有返回值,并在join()后返回
});

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

Ok(())
}

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

0 comments on commit b48d3b8

Please sign in to comment.