■ spawn 함수를 사용해 쓰레드로 병렬 계산을 처리하는 방법을 보여준다.
▶ 예제 코드 (RS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
use std::sync::mpsc; use std::thread; use std::time; fn main() { let index_array : [i64; 7] = [43, 42, 20, 39, 37, 35, 30]; let instant : time::Instant = time::Instant::now(); let (tx, rx) = mpsc::channel::<(i64, i64)>(); for index in index_array { let sender : mpsc::Sender<(i64, i64)> = tx.clone(); thread::spawn ( move || { let fibonacci_sequence : i64 = calculate_fibonacci_sequence(index); sender.send((index, fibonacci_sequence)).unwrap(); } ); } let mut job_count : usize = index_array.len(); loop { if let Ok((index, fibonacci_sequence)) = rx.recv() { job_count -= 1; println!("[결과] (남은 계산 : {}) {} 번째 피보나치 수 : {} ", job_count, index, fibonacci_sequence); if job_count <= 0 { let duration : time::Duration = instant.elapsed(); println!("실행 시간 : {:?}", duration); break; } } thread::sleep(time::Duration::from_millis(300)); } } fn calculate_fibonacci_sequence(index : i64) -> i64 { if index == 1 { return 0; } if index == 2 { return 1; } return calculate_fibonacci_sequence(index - 2) + calculate_fibonacci_sequence(index - 1); } |