[Rust] 9장 동시성

1. 스레드 (Threads)

Rust에서 동시성을 처리하는 방법으로는 여러가지 방법이 있습니다. Rust의 동시성 모델은 안전성과 성능을 강조해, 주로 스레드와 비동기 프로그래밍을 통해 구현됩니다. 먼저 스레드는 표준 라이브러리에서 쉽게 생성할 수 있습니다. std:thread 모듈을 사용하여 스레드를 생성하고 관리합니다.

use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..5 {
            println!("Threads: {}", i);
        }
    });

    for i in 1..3 {
        println!("Main Threads: {}", i);
    }

    handle.join().unwrap(); // Treads end..wait
}

2. 메시지 패싱 (Message Passing)

Rust의 동시성 모델은 데이터 경쟁을 방지하기 위한 메시지 패싱을 권장하며, std::sync::mpsc 모듈을 사용하여 스레드 간에 메시지를 전송할 수 있습니다.

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        for i in 1..5 {
            tx.send(i).unwrap();
        }
    });

    for received in rx {
        println!("Result: {}", received);
    }
}

3. 비동기 프로그래밍 (Async)

Rust에서는 async/await 구문을 사용하여 비동기 프로그래밍을 지원하며, tokio나 async-std와 같은 비동기 런타임을 사용할 수 있습니다.

use async_std::task;

fn main() {
    task::block_on(async {
        let task1 = task::spawn(async {
            for i in 1..5 {
                println!("Async Work 1: {}", i);
                async_std::task::sleep(std::time::Duration::from_millis(500)).await; // 0.5 sec wait 
            }
        });

        let task2 = task::spawn(async {
            for i in 1..3 {
                println!("Async Work 2: {}", i);
                async_std::task::sleep(std::time::Duration::from_millis(300)).await; // 0.3 set wait 
            }
        });

        task1.await;
        task2.await;
    })
}
cargo run

4. Arc와 Mutex

스레드 간 데이터를 안전하게 공유하기 위해 Arc(Atomic Reference Counting)와 Mutex(Mutal Exclusion)를 사용할 수 있습니다. 

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 Results: {}", *counter.lock().unwrap());
}

 

GitHub - Koras02/rust-tutorial: https://thinky.tistory.com/category/Back-End/Rust

https://thinky.tistory.com/category/Back-End/Rust. Contribute to Koras02/rust-tutorial development by creating an account on GitHub.

github.com

 

LIST

'Back-End > Rust' 카테고리의 다른 글

[Rust] 11장 고차 함수  (0) 2025.04.04
[Rust] 10장 트레이트  (0) 2025.03.25
[Rust] 8장 제네릭  (0) 2025.03.12
[Rust] 7장 모듈  (0) 2025.03.10
[Rust] 6장 에러 처리  (0) 2025.03.08