thread

Thread

rust의 thread 기능은 1:1모델로, 각 thread를 kernel thread로 띄운다.

Example

  • thread::spawn을 사용해서 새로운 스레드를 생성할 수 있다.
  • thread::spawn는 JoinHandle을 반환하고 그것으로 join을 시킬 수 있다.
  • 또한 클로저 앞의 move를 사용해서 클로저 안에서 사용하는 변수들의 소유권을 클로저로 보낼 수 있다.
use std::thread;
use std::time::Duration;

fn main() {
    let v = vec![1, 2, 3];
    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}