<예제 코드_1>
use std::thread;
use std::sync::mpsc;
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);
}
<예제 코드_2>
use std::thread;
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("Greetings");
tx.send(val).unwrap();
println!("val is {}", val);
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
[실행 결과]
error[E0382]: use of moved value: `val`
--> src/main.rs:10:31
|
9 | tx.send(val).unwrap();
| --- value moved here
10 | println!("val is {}", val);
| ^^^ value used here after move
|
= note: move occurs because `val` has type `std::string::String`, which does
not implement the `Copy` trait
<예제 코드_3>
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("Greetings"),
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);
}
}
<예제 코드_4>
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
let tx_1 = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let vals = vec![
String::from("Greetings"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx_1.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);
}
}
<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch16-02-message-passing.html
<참조 2>
'Rust' 카테고리의 다른 글
[Rust] Trait 예제 (44일차) (0) | 2023.01.27 |
---|---|
[Rust] 공유 상태 동시성 예제 (Shared State Concurrency, 43일차) (0) | 2023.01.26 |
[Rust] Concurrency : Thread 예제 (41일차) (0) | 2023.01.24 |
[Rust] Circular Reference (순환 참조) 예제 (40일차) (0) | 2023.01.23 |
댓글