Pin

Async blocks and functions return types implementing the Future trait. The type returned is the result of a compiler transformation which turns local variables into data stored inside the future.

Some of those variables can hold pointers to other local variables. Because of that, the future should never be moved to a different memory location, as it would invalidate those pointers.

To prevent moving the future type in memory, it can only be polled through a pinned pointer. Pin is a wrapper around a reference that disallows all operations that would move the instance it points to into a different memory location.

use tokio::sync::{mpsc, oneshot};
use tokio::task::spawn;
use tokio::time::{sleep, Duration};

// ์ž‘์—… ํ•ญ๋ชฉ. ์ด ๊ฒฝ์šฐ ์ง€์ •๋œ ์‹œ๊ฐ„ ๋™์•ˆ ์ ˆ์ „ ๋ชจ๋“œ์ด๊ณ 
// `respond_on` ์ฑ„๋„์˜ ๋ฉ”์‹œ์ง€๋กœ ์‘๋‹ตํ•ฉ๋‹ˆ๋‹ค.
#[derive(Debug)]
struct Work {
    input: u32,
    respond_on: oneshot::Sender<u32>,
}

// ํ์—์„œ ์ž‘์—…์„ ์ˆ˜์‹  ๋Œ€๊ธฐํ•˜๊ณ  ์‹คํ–‰ํ•˜๋Š” worker์ž…๋‹ˆ๋‹ค.
async fn worker(mut work_queue: mpsc::Receiver<Work>) {
    let mut iterations = 0;
    loop {
        tokio::select! {
            Some(work) = work_queue.recv() => {
                sleep(Duration::from_millis(10)).await; // ์ž‘์—…ํ•˜๋Š” ์ฒ™ํ•ฉ๋‹ˆ๋‹ค.
                work.respond_on
                    .send(work.input * 1000)
                    .expect("์‘๋‹ต์„ ๋ณด๋‚ด์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.");
                iterations += 1;
            }
            // TODO: 100๋ฐ€๋ฆฌ์ดˆ๋งˆ๋‹ค ๋ฐ˜๋ณต ํšŸ์ˆ˜๋ฅผ ๋ณด๊ณ ํ•ฉ๋‹ˆ๋‹ค.
        }
    }
}

// ์ž‘์—…์„ ์š”์ฒญํ•˜๊ณ  ์ž‘์—…์ด ์™„๋ฃŒ๋˜๊ธฐ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋Š” ์š”์ฒญ์ž์ž…๋‹ˆ๋‹ค.
async fn do_work(work_queue: &mpsc::Sender<Work>, input: u32) -> u32 {
    let (tx, rx) = oneshot::channel();
    work_queue
        .send(Work { input, respond_on: tx })
        .await
        .expect("์ž‘์—… ํ์—์„œ ์ „์†กํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.");
    rx.await.expect("์‘๋‹ต ๋Œ€๊ธฐ ์‹คํŒจ")
}

#[tokio::main]
async fn main() {
    let (tx, rx) = mpsc::channel(10);
    spawn(worker(rx));
    for i in 0..100 {
        let resp = do_work(&tx, i).await;
        println!("๋ฐ˜๋ณต ์ž‘์—… ๊ฒฐ๊ณผ {i}: {resp}");
    }
}
  • ์œ„์—์„œ ์†Œ๊ฐœํ•œ ๊ฒƒ์€ ์•กํ„ฐ(actor) ํŒจํ„ด์˜ ํ•œ ์˜ˆ๋ผ๊ณ  ๋ด๋„ ๋ฌด๋ฐฉํ•ฉ๋‹ˆ๋‹ค. ์•กํ„ฐ๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฃจํ”„ ์•ˆ์—์„œ select!๋ฅผ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.

  • ์ด์ „ ๊ฐ•์˜ ๋ช‡ ๊ฐœ์˜ ๋‚ด์šฉ์„ ์š”์•ฝํ•œ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ฒœ์ฒœํžˆ ์‚ดํŽด๋ณด์„ธ์š”.

    • _ = sleep(Duration::from_millis(100)) => { println!(..) }์„ select!์— ์ถ”๊ฐ€ํ•ด ๋ณด์„ธ์š”. ์ด ์ž‘์—…์€ ์‹คํ–‰๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์™œ ๊ทธ๋Ÿด๊นŒ์š”?

    • ๋Œ€์‹ , ํ•ด๋‹น future๊ฐ€ ํฌํ•จ๋œ timeout_fut๋ฅผ loop ์™ธ๋ถ€์— ์ถ”๊ฐ€ํ•ด ๋ณด์„ธ์š”.

      #![allow(unused)]
      fn main() {
      let mut timeout_fut = sleep(Duration::from_millis(100));
      loop {
          select! {
              ..,
              _ = timeout_fut => { println!(..); },
          }
      }
      }
    • ์—ฌ์ „ํžˆ ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ปดํŒŒ์ผ๋Ÿฌ ์˜ค๋ฅ˜๋ฅผ ๋”ฐ๋ผ select!์˜ timeout_fut์— &mut๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ Move ์‹œ๋ฉ˜ํ‹ฑ ๊ด€๋ จํ•œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ณ  Box::pin์„ ์‚ฌ์šฉํ•˜์„ธ์š”.

      #![allow(unused)]
      fn main() {
      let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100)));
      loop {
          select! {
              ..,
              _ = &mut timeout_fut => { println!(..); },
          }
      }
      }
    • ์ด๋Š” ์ปดํŒŒ์ผ์€ ๋˜์ง€๋งŒ ํƒ€์ž„ ์•„์›ƒ์ด ๋˜๋ฉด ๋งค๋ฒˆ ๋ฐ˜๋ณตํ•  ๋•Œ ๋งˆ๋‹ค Poll::Ready๊ฐ€ ๋ฉ๋‹ˆ๋‹ค(์œตํ•ฉ๋œ future๊ฐ€ ๋„์›€์ด ๋  ์ˆ˜ ์žˆ์Œ). ํƒ€์ž„ ์•„์›ƒ ๋  ๋•Œ๋งˆ๋‹ค timeout_fut๋ฅผ ๋ฆฌ์…‹ํ•˜๋„๋ก ์ˆ˜์ •ํ•˜์„ธ์š”.

  • Box๋Š” ํž™์— ํ• ๋‹นํ•ฉ๋‹ˆ๋‹ค. ๊ฒฝ์šฐ์— ๋”ฐ๋ผ std::pin::pin!(์ตœ๊ทผ์—์•ผ ์•ˆ์ •ํ™”๋˜์—ˆ์œผ๋ฉฐ ์ด์ „ ์ฝ”๋“œ๋Š” tokio::pin!์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์Œ)๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์ด๋Š” ์žฌํ• ๋‹น๋œ future์— ์‚ฌ์šฉํ•˜๊ธฐ๊ฐ€ ์–ด๋ ต์Šต๋‹ˆ๋‹ค.

  • ๋˜ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์€ pin์„ ์•„์˜ˆ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  100ms๋งˆ๋‹ค oneshot ์ฑ„๋„์— ์ „์†กํ•  ๋‹ค๋ฅธ ์ž‘์—…์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

  • Data that contains pointers to itself is called self-referential. Normally, the Rust borrow checker would prevent self-referential data from being moved, as the references cannot outlive the data they point to. However, the code transformation for async blocks and functions is not verified by the borrow checker.

  • Pin is a wrapper around a reference. An object cannot be moved from its place using a pinned pointer. However, it can still be moved through an unpinned pointer.

  • The poll method of the Future trait uses Pin<&mut Self> instead of &mut Self to refer to the instance. Thatโ€™s why it can only be called on a pinned pointer.