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

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

7
Cargo.lock generated
View File

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

View File

@ -14,10 +14,12 @@ members = [
"members/tokio-send-sync", "members/tokio-send-sync",
"members/matchmatchmatch", "members/matchmatchmatch",
"members/future_stream", "members/future_stream",
"members/mpsc",
] ]
default-members = [ default-members = [
".", ".",
"members/revsqrt", "members/revsqrt",
"members/mpsc",
"members/criterion-demo", "members/criterion-demo",
"members/shortc", "members/shortc",
"members/pest-demo", "members/pest-demo",

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

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

@ -0,0 +1,60 @@
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)
}
}