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 laterhandle.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 fromhandle.join()
to get access to the panic payload. This is a good time to talk aboutAny
.
์ญ์ฃผ
- ๋ค๋ฅธ์ธ์ด์ ์ค๋ ๋ === js๋ง ํ์ผ๋ฉด ํฌ๊ฒ์ดํธ ์ด๋ฆฌ๋ ์ฅ์ ๋๋ค(โฆ)
1
๋ฐ๋ชฌ ์ค๋ ๋๋ ์ผ๋ฐ ์ค๋ ๋์ ๋ณด์กฐ ์ค๋ ๋๋ก ์ฃผ ์ค๋ ๋๊ฐ ์ข ๋ฃ๋๋ฉด ๊ฐ์ด ์ข ๋ฃ๋๊ณ , ๋ฐฑ๊ทธ๋ผ์ด๋์์ ๋ฎ์ ์ฐ์ ์์๋ก ๋์ํฉ๋๋ค.
- ๋ฐ๋ชฌ: ์ฌ์ฉ์๊ฐ ์ง์ ์ ์ผ๋ก ์ ์ดํ์ง ์๊ณ ๋ฐฑ๊ทธ๋ผ์ด๋์์ ๋์ํ๋ ํ๋ก๊ทธ๋จ.