<예제 코드_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>
'Rust' 카테고리의 다른 글
[Rust] 공유 상태 동시성 예제 (Shared State Concurrency, 43일차) (0) | 2023.01.26 |
---|---|
[Rust] Concurrency : Message Passing 예제 (42일차) (0) | 2023.01.25 |
[Rust] Circular Reference (순환 참조) 예제 (40일차) (0) | 2023.01.23 |
[Rust] RefCell 예제 (39일차) (0) | 2023.01.22 |
댓글