본문으로 건너뛰기 Rust 동시성 | Thread, Channel, Arc, Mutex

Rust 동시성 | Thread, Channel, Arc, Mutex

Rust 동시성 | Thread, Channel, Arc, Mutex

이 글의 핵심

use std::thread; use std::time::Duration;.

시리즈 안내

#07 | 📋 전체 목차 | 이전: #06 컬렉션 · 다음: #08 비동기


들어가며

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 없이 스레드 간 데이터 공유를 시도하는 경우.
  • 데드락: 두 개 이상의 뮤텍스를 서로 다른 순서로 잠그는 경우.

주의사항

  • Mutexlock() 실패(panic)는 포이즌 상태를 의미할 수 있습니다.
  • Send/Sync 제약을 이해하지 못해 클로저 캡처에서 막히는 경우가 많습니다.

실무에서는 이렇게

  • CPU 병렬은 rayon, I/O 동시성은 tokio로 역할을 나눕니다.
  • 공유 상태 최소화를 위해 메시지 패싱 우선을 고려합니다.

비교 및 대안

도구용도
OS 스레드CPU 바운드, 격리
Tokio taskI/O 대기 많음
프로세스 분리강한 격리·크래시 내성

추가 리소스


정리

핵심 요약

  1. thread::spawn: 스레드 생성
  2. mpsc::channel: 스레드 간 통신
  3. Arc: 원자적 참조 카운팅 (여러 스레드 공유)
  4. Mutex: 상호 배제 (동시 접근 방지)
  5. join: 스레드 완료 대기

다음 단계


관련 글


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. Rust 동시성 use std::thread; use std::time::Duration;. 실전 예제와 코드로 개념부터 활용까지 정리합니다. Rust·동시성·Thread 중심으로 설명합니다. Start now. 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

Rust, 동시성, Thread, Concurrency 등으로 검색하시면 이 글이 도움이 됩니다.