728x90
728x170
■ spawn 함수를 사용해 쓰레드로 병렬 계산을 처리하는 방법을 보여준다.
▶ 예제 코드 (RS)
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);
}
728x90
그리드형(광고전용)
'Rust > Common' 카테고리의 다른 글
[RUST/COMMON] macro_rules! 매크로 : BASIC 언어의 for문 매크로 만들기 (0) | 2023.06.09 |
---|---|
[RUST/COMMON] macro_rules! 매크로 : 가변 인수 매크로 만들기 (0) | 2023.06.08 |
[RUST/COMMON] marco_rules! 매크로 : 매크로 만들기 (0) | 2023.06.08 |
[RUST/COMMON] 크레이트 설치 : async-std (0) | 2023.06.07 |
[RUST/COMMON] TCP 프로토콜을 사용해 간이 채팅 프로그램 만들기 (0) | 2023.06.05 |
[RUST/COMMON] Instant 구조체 : elapsed 메소드를 사용해 실행 시간 측정하기 (0) | 2023.06.04 |
[RUST/COMMON] channel 함수 : MPSC 채널 객체 생성하기 (0) | 2023.06.03 |
[RUST/COMMON] MPSC 채널 메커니즘을 사용해 스레드 간 데이터 공유하기 (0) | 2023.06.03 |
[RUST/COMMON] Duration 구조체 : from_millis 연관 함수를 사용해 1000 밀리초 Duration 객체 구하기 (0) | 2023.06.03 |
[RUST/COMMON] sleep 함수 : 쓰레드 대기하기 (0) | 2023.06.03 |