728x90

😶🌫️ 비동기 프로그래밍이란?
일반적인 프로그래밍에서는 명령이 순차적으로 실행되나, 비동기 프로그램에서는 시간이 소요되는 작업(ex.파일 읽기, 네트워크 요청 등)을 기다리지 않고, 나중에 결과가 오면 Callback(콜백)이나 Future를 통해 처리할 수 있는 방식입니다.
🛠️ 기본 문법
- async fn 함수 정의
async fn say_hello() {
println!("Hello, World!")
}
async fn은 Feture를 반환해, 즉시 실행되지 않으며, 나중에 awiat를 반환할 수 있습니다.
- await 키워드
async fn greet() {
say_hello().await;
println!("Greetings from async function!");
}
- main 함수에서 async 사용
기본적으로 Rust의 main 함수는 async를 지원하지 않습니다. 그래서 비동기 런타임을 사용해야 합니다.
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
# main.rs
#[tokio::main]
async fn main() {
say_hello().await;
}
🍎 비동기 함수와 지연 작업
use tokio::time::{sleep, Duration};
async fn do_something() {
println!("Doing something...");
sleep(Duration::from_secs(2)).await;
println!("2 seconds later, done!");
}
#[tokio::main]
async fn main() {
do_something().await;
}
- sleep(): 2초 동안 비동기 지연 작업을 수행
- await: await를 사용해 블로킹(blocking) 없이 지연될 수 있음
- tokio::main: 프로그램을 비동기적으로 실행하게 해주는 매크로
☘️ 여러작업을 동시에 실행: join!
join!을 통해 여러 비동기 작업을 동시에 실행하고 모두 완료될 때까지 기다립니다.
use tokio::join;
async fn task1() {
println!("Task 1 is running...");
}
async fn task2() {
println!("Task 2 is running...")
}
#[tokio::main]
async fn main() {
let ((), ()) = join!(task1(), task2());
println!("Both tasks completed!");
}
- join!: 여러 비동기 작업을 동시에 실행하고 모두 완료될 때 까지 기다림
- task1()과 task2()가 동시에 실행
GitHub - Koras02/rust-tutorial: https://thinky.tistory.com/category/Back-End/Rust
https://thinky.tistory.com/category/Back-End/Rust. Contribute to Koras02/rust-tutorial development by creating an account on GitHub.
github.com
728x90
LIST
'Back-End > Rust' 카테고리의 다른 글
| [Rust] 14장 매크로 (4) | 2025.08.13 |
|---|---|
| [Rust] 13장 메모리 (2) | 2025.08.09 |
| [Rust] 11장 고차 함수 (0) | 2025.04.04 |
| [Rust] 10장 트레이트 (0) | 2025.03.25 |
| [Rust] 9장 동시성 (0) | 2025.03.20 |