๊ฒฝ๊ณ„ ์ฑ„๋„

With bounded (synchronous) channels, send can block the current thread:

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::sync_channel(3);

    thread::spawn(move || {
        let thread_id = thread::current().id();
        for i in 1..10 {
            tx.send(format!("๋ฉ”์‹œ์ง€ {i}")).unwrap();
            println!("{thread_id:?}: ๋ณด๋‚ธ ๋ฉ”์‹œ์ง€ {i}");
        }
        println!("{thread_id:?}: ์™„๋ฃŒ");
    });
    thread::sleep(Duration::from_millis(100));

    for msg in rx.iter() {
        println!("๊ธฐ๋ณธ: {msg} ๋ฐ›์Œ");
    }
}
  • send๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์ฑ„๋„์— ์ƒˆ ๋ฉ”์‹œ์ง€๋ฅผ ์œ„ํ•œ ๊ณต๊ฐ„์ด ํ™•๋ณด๋  ๋•Œ๊นŒ์ง€ ํ˜„์žฌ ์Šค๋ ˆ๋“œ๊ฐ€ ์ฐจ๋‹จ๋ฉ๋‹ˆ๋‹ค. ์ฑ„๋„์—์„œ ์ฝ๋Š” ์‚ฌ๋žŒ์ด ์—†๋Š” ๊ฒฝ์šฐ ์Šค๋ ˆ๋“œ๊ฐ€ ๋ฌด๊ธฐํ•œ ์ฐจ๋‹จ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • send ํ˜ธ์ถœ์€ ์˜ค๋ฅ˜์™€ ํ•จ๊ป˜ ์ค‘๋‹จ๋ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ฑ„๋„์ด ๋‹ซํžˆ๋ฉด Result๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ˆ˜์‹ ์ž๋ฅผ ์‚ญ์ œํ•˜๋ฉด ์ฑ„๋„์ด ๋‹ซํž™๋‹ˆ๋‹ค.
  • A bounded channel with a size of zero is called a โ€œrendezvous channelโ€. Every send will block the current thread until another thread calls recv.