Threads

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

Rust threads work similarly to threads in other languages:

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

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("Count in thread: {i}!");
            thread::sleep(Duration::from_millis(5));
        }
    });

    for i in 1..5 {
        println!("Main thread: {i}");
        thread::sleep(Duration::from_millis(5));
    }
}
  • ์Šค๋ ˆ๋“œ๋Š” ๋ชจ๋‘ ๋ฐ๋ชฌ ์Šค๋ ˆ๋“œ1์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ฃผ ์Šค๋ ˆ๋“œ๋Š” ์ด๋ฅผ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • ์Šค๋ ˆ๋“œ์˜ ํŒจ๋‹‰์€ ์„œ๋กœ ๋…๋ฆฝ์ ์œผ๋กœ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค.
    • (์Šค๋ ˆ๋“œ์˜) ํŒจ๋‹‰์€ (์ฃผ ์Šค๋ ˆ๋“œ์—๊ฒŒ) ํŽ˜์ด๋กœ๋“œ๋ฅผ ์ „๋‹ฌํ•˜๊ณ , ์ด๋Š” downcast_ref๋กœ ํ’€์–ด๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • Threads are all daemon threads, the main thread does not wait for them.
  • Thread panics are independent of each other.
    • Panics can carry a payload, which can be unpacked with downcast_ref.
๊ฐ•์˜ ์ฐธ์กฐ ๋…ธํŠธ

ํ‚คํฌ์ธํŠธ:

  • ์ฃผ ์Šค๋ ˆ๋“œ๊ฐ€ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์ƒ์„ฑ๋œ ์Šค๋ ˆ๋“œ์˜ for๋ฌธ์€ 10๊นŒ์ง€ ๊ฐ€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • ๋งŒ์•ฝ ์ฃผ ์Šค๋ ˆ๋“œ๊ฐ€ ์Šค๋ ˆ๋“œ ๋™์ž‘์„ ๋Œ€๊ธฐ ํ•˜๊ธฐ ์›ํ•œ๋‹ค๋ฉด let handle = thread::spawn(...)์œผ๋กœ ์Šค๋ ˆ๋“œ๋ฅผ ์„ ์–ธํ•œ ํ›„ handle.join()๋กœ ์—ฐ๊ฒฐํ•˜์—ฌ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
  • ์Šค๋ ˆ๋“œ์—์„œ ์œ ๋ฐœ๋œ ํŒจ๋‹‰(for ๊ฐ•์ œ ์ข…๋ฃŒ)์ด ์ฃผ ์Šค๋ ˆ๋“œ์—๋Š” ์˜ํ–ฅ์ด ์—†์Œ์„ ํ™•์ธํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.
  • handle.join()์‚ฌ์šฉ์‹œ Result ๋ฐ˜ํ™˜๊ฐ’์„ ํ†ตํ•ด ํŒจ๋‹‰ ํŽ˜์ด๋กœ๋“œ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. Any๋ฅผ ์ฐธ์กฐํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

Key points:

  • Notice that the thread is stopped before it reaches 10 โ€” the main thread is not waiting.

  • Use let handle = thread::spawn(...) and later handle.join() to wait for the thread to finish.

  • Trigger a panic in the thread, notice how this doesnโ€™t affect main.

  • Use the Result return value from handle.join() to get access to the panic payload. This is a good time to talk about Any.


์—ญ์ฃผ

  • ๋‹ค๋ฅธ์–ธ์–ด์˜ ์Šค๋ ˆ๋“œ === js๋งŒ ํ–ˆ์œผ๋ฉด ํ—ฌ๊ฒŒ์ดํŠธ ์—ด๋ฆฌ๋Š” ์žฅ์ž…๋‹ˆ๋‹ค(โ€ฆ)
1

๋ฐ๋ชฌ ์Šค๋ ˆ๋“œ๋Š” ์ผ๋ฐ˜ ์Šค๋ ˆ๋“œ์˜ ๋ณด์กฐ ์Šค๋ ˆ๋“œ๋กœ ์ฃผ ์Šค๋ ˆ๋“œ๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด ๊ฐ™์ด ์ข…๋ฃŒ๋˜๊ณ , ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋‚ฎ์€ ์šฐ์„ ์ˆœ์œ„๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

  • ๋ฐ๋ชฌ: ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘์ ์œผ๋กœ ์ œ์–ดํ•˜์ง€ ์•Š๊ณ  ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋™์ž‘ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ.