mpsc
cargo devel CI / cargo CI (push) Successful in 1m49s Details

This commit is contained in:
Christoph J. Scherr 2024-02-28 11:24:03 +01:00
parent ff88f1dcb3
commit 5b594122ba
Signed by: cscherrNT
GPG Key ID: 8E2B45BC51A27EA7
4 changed files with 81 additions and 0 deletions

7
Cargo.lock generated
View File

@ -890,6 +890,13 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "mpsc"
version = "0.1.0"
dependencies = [
"anyhow",
]
[[package]]
name = "nom"
version = "7.1.3"

View File

@ -14,10 +14,12 @@ members = [
"members/tokio-send-sync",
"members/matchmatchmatch",
"members/future_stream",
"members/mpsc",
]
default-members = [
".",
"members/revsqrt",
"members/mpsc",
"members/criterion-demo",
"members/shortc",
"members/pest-demo",
@ -31,6 +33,7 @@ default-members = [
"members/matchmatchmatch",
"members/future_stream",
]
publish = false
[workspace.dependencies]
anyhow = "1.0.79"

9
members/mpsc/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "mpsc"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow.workspace = true

62
members/mpsc/src/main.rs Normal file
View File

@ -0,0 +1,62 @@
//! Example on how to use std::mpsc with 2 threads
use anyhow::Result;
use std::io::Write;
use std::str::FromStr;
use std::sync::{Arc, Barrier};
use std::{sync::mpsc, thread};
#[derive(Clone, Debug)]
struct Message {
payload: String,
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Message {{{}}}", self.payload)
}
}
impl std::str::FromStr for Message {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
Ok(Self {
payload: s.to_string(),
})
}
}
fn printer(receiver: mpsc::Receiver<Message>, barrier: Arc<Barrier>) -> Result<()> {
let mut stdout = std::io::stdout();
loop {
let msg = receiver.recv()?;
println!("{msg}");
stdout.flush()?;
barrier.wait(); // wait until the main thread wants us to print
}
}
fn main() -> Result<()> {
let (sender, receiver) = mpsc::channel();
let barrier = Arc::new(Barrier::new(2));
let barrier_printer = barrier.clone();
thread::spawn(|| printer(receiver, barrier_printer).expect("printer error"));
let mut msg;
let mut buf = String::new();
let stdin = std::io::stdin();
let mut stdout = std::io::stdout();
loop {
buf.clear();
print!("> ");
stdout.flush()?;
let _ = stdin.read_line(&mut buf)?;
buf = buf.replace('\n', "");
if buf.is_empty() {
continue;
}
msg = Message::from_str(&buf).unwrap();
sender.send(msg)?;
barrier.wait(); // wait until the printer is done printing the message, so we dont mix
// stdout prints (we use print instead of println)
}
}