Rust 동시성 | Thread, Channel, Arc, Mutex
이 글의 핵심
Rust 동시성에 대해 정리한 개발 블로그 글입니다. use std::thread; use std::time::Duration;
들어가며
Rust는 데이터 레이스를 컴파일 단계에서 막는 쪽에 가깝습니다. 스레드 간 공유는 Arc·Mutex로, 메시지 전달은 채널로 처리하는 패턴이 흔합니다. 공유 자원의 열쇠를 누가 쥐는지가 여전히 소유권 규칙과 연결됩니다.
Go의 고루틴·채널도 “통신으로 동기화” 쪽에 서고, Kotlin 코루틴은 스레드 풀·디스패처 위에서 협력적으로 돌아갑니다. OS 스레드를 직접 다루는 흐름은 Java Thread·C++ std::thread와 나란히 보면 좋습니다.
1. 스레드 (Thread)
기본 스레드
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("스레드: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
for i in 1..5 {
println!("메인: {}", i);
thread::sleep(Duration::from_millis(100));
}
handle.join().unwrap();
}
데이터 전달
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("벡터: {:?}", v);
});
handle.join().unwrap();
// v는 더 이상 사용 불가 (소유권 이동)
}
2. 채널 (Channel)
기본 채널
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("안녕하세요");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("받음: {}", received);
}
여러 메시지
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_millis(100));
}
});
for received in rx {
println!("받음: {}", received);
}
}
여러 송신자
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let tx2 = tx.clone();
thread::spawn(move || {
tx.send(String::from("스레드 1")).unwrap();
});
thread::spawn(move || {
tx2.send(String::from("스레드 2")).unwrap();
});
for received in rx {
println!("받음: {}", received);
}
}
3. Arc와 Mutex
Mutex (상호 배제)
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut num = m.lock().unwrap();
*num = 6;
} // 락 해제
println!("m = {:?}", m);
}
Arc + Mutex
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("결과: {}", *counter.lock().unwrap()); // 10
}
4. 실전 예제
예제: 병렬 계산
use std::thread;
use std::sync::{Arc, Mutex};
fn parallel_sum(numbers: Vec<i32>) -> i32 {
let chunk_size = numbers.len() / 4;
let numbers = Arc::new(numbers);
let result = Arc::new(Mutex::new(0));
let mut handles = vec![];
for i in 0..4 {
let numbers = Arc::clone(&numbers);
let result = Arc::clone(&result);
let handle = thread::spawn(move || {
let start = i * chunk_size;
let end = if i == 3 { numbers.len() } else { (i + 1) * chunk_size };
let sum: i32 = numbers[start..end].iter().sum();
let mut total = result.lock().unwrap();
*total += sum;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
*result.lock().unwrap()
}
fn main() {
let numbers: Vec<i32> = (1..=1000).collect();
let sum = parallel_sum(numbers);
println!("합계: {}", sum); // 500500
}
실전 심화 보강
실전 예제: 데이터 청크를 스레드로 나누어 합산 (표준 라이브러리만)
std::mpsc::Receiver는 복제할 수 없어 “여러 워커가 한 큐를 나눠 먹기” 패턴을 그대로 구현하기 어렵습니다. 그 대신 데이터를 미리 청크로 나눈 뒤 스레드마다 한 청크만 처리하면 동일한 효과를 얻을 수 있습니다.
use std::thread;
fn parallel_sum(nums: Vec<i32>, workers: usize) -> i32 {
assert!(workers > 0);
let chunk_size = (nums.len() + workers - 1) / workers;
let chunks: Vec<Vec<i32>> = nums
.chunks(chunk_size.max(1))
.map(|c| c.to_vec())
.collect();
let handles: Vec<_> = chunks
.into_iter()
.map(|chunk| {
thread::spawn(move || chunk.iter().copied().sum::<i32>())
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).sum()
}
fn main() {
let nums: Vec<i32> = (1..=10_000).collect();
let total = parallel_sum(nums, 4);
println!("합계: {}", total);
}
자주 하는 실수
Mutex락을 잡은 채로 I/O를 하여 다른 스레드를 굶기는 경우.Arc없이 스레드 간 데이터 공유를 시도하는 경우.- 데드락: 두 개 이상의 뮤텍스를 서로 다른 순서로 잠그는 경우.
주의사항
Mutex의lock()실패(panic)는 포이즌 상태를 의미할 수 있습니다.Send/Sync제약을 이해하지 못해 클로저 캡처에서 막히는 경우가 많습니다.
실무에서는 이렇게
- CPU 병렬은
rayon, I/O 동시성은 **tokio**로 역할을 나눕니다. - 공유 상태 최소화를 위해 메시지 패싱 우선을 고려합니다.
비교 및 대안
| 도구 | 용도 |
|---|---|
| OS 스레드 | CPU 바운드, 격리 |
| Tokio task | I/O 대기 많음 |
| 프로세스 분리 | 강한 격리·크래시 내성 |
추가 리소스
정리
핵심 요약
- thread::spawn: 스레드 생성
- mpsc::channel: 스레드 간 통신
- Arc: 원자적 참조 카운팅 (여러 스레드 공유)
- Mutex: 상호 배제 (동시 접근 방지)
- join: 스레드 완료 대기
다음 단계
- Rust 비동기
- Rust 웹 개발
- Rust 테스팅
관련 글
- C++ 메모리 모델 |
- C++ 멀티스레딩 |
- C++ vs Rust 완전 비교 | 소유권·메모리 안전성·에러 처리·동시성·성능 실전 가이드
- Java 멀티스레드 | Thread, Runnable, Executor
- C++ Atomic |