Open3

rust

fork-join

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

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

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

    handle.join().unwrap()
}
main thread #1
the spawned thread #1
main thread #2
main thread #3
main thread #4
the spawned thread #2
the spawned thread #3
the spawned thread #4
the spawned thread #5
the spawned thread #6
the spawned thread #7
the spawned thread #8
the spawned thread #9

待たないと、先にmainスレッドが終了するので、こうなる。

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

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

    for i in 1..5 {
        println!("main thread #{}", i);
        thread::sleep(Duration::from_millis(1));
    }
    
   // joinしない
   // handle.join().unwrap()
}
main thread #1
the spawned thread #1
main thread #2
main thread #3
main thread #4
ログインするとコメントできます