async/await

๊ฒ‰์—์„œ ๋ณด์•˜์„ ๋•Œ, ๋น„๋™๊ธฐ Rust ์ฝ”๋“œ๋Š” ์ผ๋ฐ˜์ ์ธ ์ ˆ์ฐจ์  ์ฝ”๋“œ์™€ ๋งค์šฐ ์œ ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

use futures::executor::block_on;

async fn count_to(count: i32) {
    for i in 1..=count {
        println!("์ˆ˜: {i}๊ฐœ!");
    }
}

async fn async_main(count: i32) {
    count_to(count).await;
}

fn main() {
    block_on(async_main(10));
}

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

  • Rust ๋น„๋™๊ธฐ ๋ฌธ๋ฒ•์„ ๋ณด์—ฌ์ฃผ๋Š” ๊ฐ„๋‹จํ•œ ์˜ˆ์‹œ์ž…๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์—๋Š” ์˜ค๋ž˜ ์‹คํ–‰๋˜๋Š” ์ž‘์—…์ด๋‚˜, ์‹ค์ œ๋กœ ๋™์‹œ์— ์ˆ˜ํ–‰๋˜๋Š” ๊ฒƒ๋“ค์€ ์—†์Šต๋‹ˆ๋‹ค.

  • asyncํ•จ์ˆ˜์˜ ๋ฆฌํ„ด ํƒ€์ž…์€ ๋ฌด์—‡์ธ๊ฐ€์š”?

    • main์—์„œ `let future: () = async_main(10);์„ ์‚ฌ์šฉํ•˜์—ฌ ํƒ€์ž…์„ ํ™•์ธํ•˜์„ธ์š”.
  • The โ€œasyncโ€ keyword is syntactic sugar. The compiler replaces the return type with a future.

  • main์„ ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์ˆ˜๋Š” ์—†์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ทธ๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ๋ฆฌํ„ด ํƒ€์ž…์ธ future๋ฅผ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•  ์ง€ ๋ชจ๋ฅด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

  • You need an executor to run async code. block_on blocks the current thread until the provided future has run to completion.

  • .await๋Š” ๋‹ค๋ฅธ ์ž‘์—…์ด ์™„๋ฃŒ๋  ๋•Œ๊นŒ์ง€ ๋น„๋™๊ธฐ์ ์œผ๋กœ ๋Œ€๊ธฐํ•ฉ๋‹ˆ๋‹ค. block_on๊ณผ ๋‹ฌ๋ฆฌ .await๋Š” ํ˜„์žฌ ์Šค๋ ˆ๋“œ๋ฅผ ๋ธ”๋กํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

  • .await can only be used inside an async function (or block; these are introduced later).