Rust, Concurrency and Channels
Rust 프로그래밍에서 concurrency 모델의 핵심 메커니즘을 비교적 간단한 소스 코드를 통하여 단계별로 정리해보았다.1
Go(lang)에서 goroutine, channel을 사용하여 함수와 메소드의 동시성을 구현할 수 있게 해주는 것2처럼 Rust에서는 ‘Concurrency, Threads, Channels, Mutex and Arc’로 동시성을 구현할 수 있다.
기본 Thread 구현 및 한계
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("vector: {:?}", v);
});
// - error : value borrowed here after move
// println!("{:?}", v);
// - channel을 이용하여 해결
handle.join().unwrap();
}
1
2
3
4
5
6
7
8
9
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send(42).unwrap();
});
println!("get {}", rx.recv().unwrap());
}