본문 바로가기
Rust

[Rust] Concurrency : Thread 예제 (41일차)

by 꾸압 2023. 1. 24.

 

<예제 코드_1>

use std::thread;

let handle = thread::spawn(|| {
    println!("Running in a new thread!");
})

 


 

<예제 코드_2>

use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}

 


 

<예제 코드_3>

use std::thread;

struct MyStruct {
    data: i32,
}

impl MyStruct {
    fn new(data: i32) -> MyStruct {
        MyStruct { data }
    }

    fn run(&self) {
        println!("Running in a new thread with data={}", self.data);
    }
}

fn main() {
    let my_struct = MyStruct::new(5);
    let handle = thread::spawn(move || {
        my_struct.run();
    });

    handle.join().unwrap();
}

 


 

<예제 코드_4>

==> Thread와 For문이 동시 동작

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("Hi number {} form the spawned thread", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

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

    handle.join().unwrap();
}

 


 

<예제 코드_5>

==> Main Thread가 실행된 후 for문이 동작

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("Hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    handle.join().unwrap();

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

 


 

<예제 코드_6>

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let data = Arc::new(Mutex::new(vec![1, 2, 3]));

    let data_clone = data.clone();
    let handle = thread::spawn(move || {
        let mut data = data_clone.lock().unwrap();
        data.push(4);
    });

    handle.join().unwrap();

    let data = data.lock().unwrap();
    println!("Data in the main thread: {:?}", data);
}

 

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch16-01-threads.html

<참조 2> https://chat.openai.com/chat

<참조 3>

 

 

댓글