Notes
- A process should always ask OS kernel first and then interact with another process
- in Rust, to spawn a new thread:
use std::thread;
fn main(){
thread::spawn(f);
}
fn f() {
// ...function to do
}
- The Rust standard library assigns every thread a unique identifier. This identifier is accessible through
Thread::id()
and is of the typeThreadId
. Rach ID will be different but not consecutively - Returning from main thread will exit the entire program, even if other threads are still running.
// To make sure the threads are finished before we return from main
fn main() {
let t1 = thread::spawn(f);
let t2 = thread::spawn(f);
println!("Hello from the main thread.");
// use JoinHandle to ahcieve it
// The .join() method waits until the thread has finished executing
// and returns a std::thread::Result.
// unwrap() is for panic
t1.join().unwrap();
t2.join().unwrap();
}
在 Rust 中,”panic” 是一種用於處理錯誤的機制。當程式遇到無法處理的錯誤時,它會拋出一個 panic,並停止執行