Skip to content

Instantly share code, notes, and snippets.

@decatur
Created November 4, 2025 00:11
Show Gist options
  • Save decatur/c428f40c94ae49e1646d192d7fe28c07 to your computer and use it in GitHub Desktop.
Save decatur/c428f40c94ae49e1646d192d7fe28c07 to your computer and use it in GitHub Desktop.
Threads can have task xor service semantics
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use rayon::prelude::*;
fn main() {
let (tx, rx): (Sender<u8>, Receiver<u8>) = mpsc::channel();
// Thread as an event loop (service)
// Long lived
// May use messaging and shared state
std::thread::spawn(move || {
loop {๐Ÿ˜‰
// let e = events.next();
// do_sume_cool_stuff(e);
let e = rx.recv().unwrap();
println!("{e}");
if e == 3 {
break
}
}
});
// Thread as a parallel function (task)
// Only input and output
// No messaging unless being silly.
// Maybe shared state
fn my_func(i: u8) -> u8 { i * i }
let input = [(1u8, tx.clone()), (2u8, tx.clone()), (3u8, tx.clone())];
let r: u8 = input.par_iter()
.map(|(i, tx)| {
tx.send(*i).unwrap(); // Ok, we are silly ๐Ÿ˜‰
my_func(*i)
})
.sum();
assert_eq!(r, 14);
println!("Exit");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment