์Šค๋ ˆ๋“œ

๋Ÿฌ์ŠคํŠธ์˜ ์Šค๋ ˆ๋“œ๋Š” ๋‹ค๋ฅธ ์–ธ์–ด์˜ ์Šค๋ ˆ๋“œ์™€ ์œ ์‚ฌํ•˜๊ฒŒ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค:

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

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("์Šค๋ ˆ๋“œ์˜ ๊ฐœ์ˆ˜: {i}!");
            thread::sleep(Duration::from_millis(5));
        }
    });

    for i in 1..5 {
        println!("๊ธฐ๋ณธ ์Šค๋ ˆ๋“œ: {i}");
        thread::sleep(Duration::from_millis(5));
    }
}
  • ์Šค๋ ˆ๋“œ๋Š” ๋ชจ๋‘ ๋ฐ๋ชฌ ์Šค๋ ˆ๋“œ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฉ”์ธ ์Šค๋ ˆ๋“œ๋Š” ์ด ์Šค๋ ˆ๋“œ๋“ค์ด ๋๋‚˜๊ธฐ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • ํ•œ ์Šค๋ ˆ๋“œ์—์„œ ๋ฐœ์ƒํ•œ ํŒจ๋‹‰์€ ๋‹ค๋ฅธ ์Šค๋ ˆ๋“œ์—๊ฒŒ ์˜ํ–ฅ์„ ๋ผ์น˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    • ํŒจ๋‹‰์€ ์ถ”๊ฐ€์ •๋ณด(ํŽ˜์ด๋กœ๋“œ)๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์ด๋Š” downcast_ref๋กœ ํ’€์–ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • Rust thread APIs look not too different from e.g. C++ ones.

  • Run the example.

    • 5ms timing is loose enough that main and spawned threads stay mostly in lockstep.
    • Notice that the program ends before the spawned thread reaches 10!
    • This is because main ends the program and spawned threads do not make it persist.
      • Compare to pthreads/C++ std::thread/boost::thread if desired.
  • How do we wait around for the spawned thread to complete?

  • thread::spawn returns a JoinHandle. Look at the docs.

    • JoinHandle has a .join() method that blocks.
  • Use let handle = thread::spawn(...) and later handle.join() to wait for the thread to finish and have the program count all the way to 10.

  • Now what if we want to return a value?

  • Look at docs again:

  • Use the Result return value from handle.join() to get access to the returned value.

  • Ok, what about the other case?

    • Trigger a panic in the thread. Note that this doesnโ€™t panic main.
    • Access the panic payload. This is a good time to talk about Any.
  • Now we can return values from threads! What about taking inputs?

    • Capture something by reference in the thread closure.
    • An error message indicates we must move it.
    • Move it in, see we can compute and then return a derived value.
  • If we want to borrow?

    • Main kills child threads when it returns, but another function would just return and leave them running.
    • That would be stack use-after-return, which violates memory safety!
    • How do we avoid this? see next slide.