Created
November 4, 2025 00:11
-
-
Save decatur/c428f40c94ae49e1646d192d7fe28c07 to your computer and use it in GitHub Desktop.
Threads can have task xor service semantics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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