Archive/Rust

[Rustlings] 18. thread

rust도 병렬 프로그래밍을 지원한다. thread::spawn을 통해 스레드를 생성하고 join함수를 통해 해당 스레드를 실행할 수 있다.

let handle = thread::spawn(|| {
  for i in 0..10 {
    println!("thread : {}", i);
  }
});

handle.join().unwrap();

thread::spawn에 실행할 코드를 클로저로 전달한다. 만약 해당 클로저가 클로저 밖의 변수를 사용한다면 그 변수의 소유권을 클로저로 넘겨야한다. 해당 클로저 앞에 move를 붙이면 클로저가 사용하는 변수의 소유권을 가져온다.

let v = vec![1, 2, 3];

let handle = thread::spawn(move || {
  for i in v {
    println!("thread : {}", i);
  }
}

handle.join().unwrap();

만약 여러 스레드와 어떤 데이터를 공유하고 싶다면 Arc을 사용한다. 다만 Arc만 이용하면 해당 데이터에 대해 읽기만 가능하기 때문에 변수의 데이터가 스레드 처리로 바뀔 수 있다면 Mutex도 같이 사용한다.

let v = Arc::new(vec![1,2,3,4,5]);
let amount = Arc::new(Mutex::new(0));
let mut handles = vec![];

for _ in 0..10 {
  let v = v.clone();
  let amount = arc.clone();
  let handle = thread::spawn(move || {
    let mut amount = amount.lock().unwrap();
    for i in v.iter() {
      *amount += i;
    }
  });
  handles.push(handle);
}

for h in handles {
  h.join().unwrap();
}

println!("amount : {}", *amount.lock().unwrap());

 

'Archive > Rust' 카테고리의 다른 글

[Rustlings] 19. macro  (0) 2021.06.12
[Rustlings] 17. Standard Library Types  (0) 2021.06.04
[Rustlings] 16. Testing  (0) 2021.06.01
[Rustlings] 15. trait  (0) 2021.05.31
[Rustlings] 14. Result  (0) 2021.05.30