2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:04:36 +00:00
|
|
|
date: 20200930
|
2024-05-06 20:40:05 +00:00
|
|
|
id: 20a442a2-657a-4337-b82f-5b7f29eb4607
|
|
|
|
title: Rust message passing
|
|
|
|
---
|
|
|
|
|
|
|
|
# Example
|
|
|
|
|
|
|
|
## Sending single value
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
use std::sync::mpsc;
|
|
|
|
use std::thread;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
|
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
let val = String::from("hi");
|
|
|
|
tx.send(val).unwrap();
|
|
|
|
});
|
|
|
|
|
|
|
|
let received = rx.recv().unwrap();
|
|
|
|
println!("Got: {}", received);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Sending multiple values
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
use std::sync::mpsc;
|
|
|
|
use std::thread;
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
|
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
let vals = vec![
|
|
|
|
String::from("hi"),
|
|
|
|
String::from("from"),
|
|
|
|
String::from("the"),
|
|
|
|
String::from("thread"),
|
|
|
|
];
|
|
|
|
|
|
|
|
for val in vals {
|
|
|
|
tx.send(val).unwrap();
|
|
|
|
thread::sleep(Duration::from_secs(1));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
for received in rx {
|
|
|
|
println!("Got: {}", received);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Creating multiple Producers
|
|
|
|
|
|
|
|
``` rust
|
|
|
|
use std::sync::mpsc;
|
|
|
|
use std::thread;
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// --snip--
|
|
|
|
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
|
|
|
|
|
|
let tx1 = mpsc::Sender::clone(&tx);
|
|
|
|
thread::spawn(move || {
|
|
|
|
let vals = vec![
|
|
|
|
String::from("hi"),
|
|
|
|
String::from("from"),
|
|
|
|
String::from("the"),
|
|
|
|
String::from("thread"),
|
|
|
|
];
|
|
|
|
|
|
|
|
for val in vals {
|
|
|
|
tx1.send(val).unwrap();
|
|
|
|
thread::sleep(Duration::from_secs(1));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
thread::spawn(move || {
|
|
|
|
let vals = vec![
|
|
|
|
String::from("more"),
|
|
|
|
String::from("messages"),
|
|
|
|
String::from("for"),
|
|
|
|
String::from("you"),
|
|
|
|
];
|
|
|
|
|
|
|
|
for val in vals {
|
|
|
|
tx.send(val).unwrap();
|
|
|
|
thread::sleep(Duration::from_secs(1));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
for received in rx {
|
|
|
|
println!("Got: {}", received);
|
|
|
|
}
|
|
|
|
|
|
|
|
// --snip--
|
|
|
|
}
|
|
|
|
```
|