Rust 주요 주제
Rust Threads: spawn and join
Run code in parallel with thread::spawn and collect each result with join.
배울 내용
- thread::spawn
- move closures
- join and return values
Three workers
- 1
spawn x3threads start - 2
sumeach works alone - 3
join()wait for each - 4
resultsprinted in order
Work that runs at the same time
A thread runs a piece of code at the same time as the rest of the program. thread::spawn starts one and returns a handle that you can use to wait for it.
move gives each thread its own copy of id. The threads may finish in any order, but join waits for each handle in the order they were created, so the output is always the same. join returns the value the closure produced.
핵심 포인트
- spawn starts a thread and returns a handle.
- move gives the thread its own data.
- join waits and returns the thread's value.
실행 가능한 Rust 예제
Rust
main.rs
use std::thread;
fn main() {
let mut handles = Vec::new();
for id in 1..=3u64 {
let handle = thread::spawn(move || {
let total: u64 = (1..=id * 1000).sum();
(id, total)
});
handles.push(handle);
}
for handle in handles {
let (id, total) = handle.join().unwrap();
println!("worker {id} summed to {total}");
}
}
worker 1 summed to 500500
worker 2 summed to 2001000
worker 3 summed to 4501500연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지