Asynchronous programming is essential for high-performance I/O-bound applications. This chapter explores how Rust's async/await works under the hood and how to use it effectively.
At the core of async Rust is the Future trait. Let's understand what it really means:
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
// The actual Future trait (simplified)
pub trait SimpleFuture {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
// Poll is an enum
pub enum Poll<T> {
Ready(T), // Future completed with value
Pending, // Future not ready yet
}
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
struct Delay {
when: Instant,
}
impl Delay {
fn new(duration: Duration) -> Self {
Delay {
when: Instant::now() + duration,
}
}
}
impl Future for Delay {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if Instant::now() >= self.when {
Poll::Ready(())
} else {
// Tell the executor to poll again
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[tokio::main]
async fn main() {
let delay = Delay::new(Duration::from_secs(1));
delay.await;
println!("Done!");
}
// Async function
async fn fetch_data(url: &str) -> Result<String, String> {
// Simulated async work
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
Ok(format!("Data from {}", url))
}
// Async block
fn create_future() -> impl Future<Output = i32> {
async {
42
}
}
// Using async/await
#[tokio::main]
async fn main() {
// Sequential
let data1 = fetch_data("api.example.com/1").await.unwrap();
let data2 = fetch_data("api.example.com/2").await.unwrap();
println!("{}\n{}", data1, data2);
}
use tokio::join;
use tokio::time::{sleep, Duration};
async fn task1() -> String {
sleep(Duration::from_millis(100)).await;
"Task 1 done".to_string()
}
async fn task2() -> String {
sleep(Duration::from_millis(100)).await;
"Task 2 done".to_string()
}
#[tokio::main]
async fn main() {
// Run concurrently (not parallel - same thread!)
let (result1, result2) = join!(task1(), task2());
println!("{}", result1);
println!("{}", result2);
}
// For dynamic number of tasks
async fn fetch_all(urls: Vec<String>) -> Vec<Result<String, String>> {
let tasks: Vec<_> = urls
.into_iter()
.map(|url| tokio::spawn(async move {
fetch_data(&url).await
}))
.collect();
let mut results = Vec::new();
for task in tasks {
results.push(task.await.unwrap());
}
results
}
use tokio::runtime::Runtime;
fn main() {
// Multi-threaded runtime (default)
let runtime = Runtime::new().unwrap();
runtime.block_on(async {
println!("Running on multi-threaded runtime");
});
// Current thread runtime (single-threaded)
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
println!("Running on current thread");
});
// Custom configuration
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.thread_name("my-worker")
.thread_stack_size(3 * 1024 * 1024)
.enable_all()
.build()
.unwrap();
}
use tokio::task;
#[tokio::main]
async fn main() {
// Spawn a task
let handle = task::spawn(async {
println!("Task running on tokio thread pool");
42
});
let result = handle.await.unwrap();
println!("Result: {}", result);
// Spawn blocking (for CPU-intensive work)
let handle = task::spawn_blocking(|| {
// This runs on a dedicated thread pool
println!("CPU-intensive work");
expensive_computation()
});
handle.await.unwrap();
}
fn expensive_computation() -> u64 {
(0..1_000_000).sum()
}
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(32);
// Spawn sender task
tokio::spawn(async move {
for i in 0..10 {
tx.send(i).await.unwrap();
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
});
// Receive in main task
while let Some(value) = rx.recv().await {
println!("Received: {}", value);
}
}
// Bounded vs Unbounded
async fn channel_types() {
// Bounded: sender waits if full
let (tx, rx) = mpsc::channel::<i32>(100);
// Unbounded: never blocks (use carefully!)
let (tx_unbounded, rx_unbounded) = mpsc::unbounded_channel::<i32>();
}
use tokio::sync::{broadcast, watch};
#[tokio::main]
async fn main() {
// Broadcast: multiple receivers
let (tx, _rx) = broadcast::channel(16);
let mut rx1 = tx.subscribe();
let mut rx2 = tx.subscribe();
tokio::spawn(async move {
tx.send("Hello").unwrap();
});
println!("rx1: {}", rx1.recv().await.unwrap());
println!("rx2: {}", rx2.recv().await.unwrap());
// Watch: single-value state channel
let (tx, mut rx) = watch::channel("initial");
tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
tx.send("updated").unwrap();
});
rx.changed().await.unwrap();
println!("Value changed to: {}", *rx.borrow());
}
use tokio::sync::Mutex;
use std::sync::Arc;
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = tokio::spawn(async move {
let mut num = counter.lock().await;
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.await.unwrap();
}
println!("Counter: {}", *counter.lock().await);
}
tokio::sync::Mutex: For holding locks across await pointsstd::sync::Mutex: For short, non-async critical sections (faster)use tokio::sync::{RwLock, Semaphore};
#[tokio::main]
async fn main() {
// RwLock: multiple readers or single writer
let lock = Arc::new(RwLock::new(5));
let read = lock.read().await;
println!("Value: {}", *read);
drop(read);
let mut write = lock.write().await;
*write += 1;
// Semaphore: limit concurrent access
let semaphore = Arc::new(Semaphore::new(3));
let mut handles = vec![];
for i in 0..10 {
let sem = semaphore.clone();
handles.push(tokio::spawn(async move {
let _permit = sem.acquire().await.unwrap();
println!("Task {} acquired permit", i);
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}));
}
for handle in handles {
handle.await.unwrap();
}
}
Race multiple futures and handle whichever completes first:
use tokio::select;
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let mut interval = tokio::time::interval(Duration::from_secs(1));
select! {
_ = sleep(Duration::from_secs(5)) => {
println!("5 second timeout");
}
_ = interval.tick() => {
println!("Interval fired");
}
}
// With cancellation
let operation = async {
sleep(Duration::from_secs(10)).await;
"Completed"
};
let timeout = sleep(Duration::from_secs(2));
select! {
result = operation => {
println!("Operation: {}", result);
}
_ = timeout => {
println!("Timed out!");
}
}
}
use tokio_stream::{self as stream, StreamExt};
#[tokio::main]
async fn main() {
// Create a stream
let mut stream = stream::iter(vec![1, 2, 3, 4, 5]);
// Process with combinator methods
while let Some(value) = stream.next().await {
println!("{}", value);
}
// Advanced stream processing
let stream = stream::iter(1..=10)
.filter(|x| x % 2 == 0)
.map(|x| x * 2);
let results: Vec<_> = stream.collect().await;
println!("{:?}", results);
// Merge multiple streams
let s1 = stream::iter(vec![1, 2, 3]);
let s2 = stream::iter(vec![4, 5, 6]);
let merged = stream::iter(vec![s1, s2]).flatten();
}
use tokio::try_join;
async fn fallible_task1() -> Result<i32, String> {
Ok(1)
}
async fn fallible_task2() -> Result<i32, String> {
Err("Task 2 failed".to_string())
}
#[tokio::main]
async fn main() {
// Early return on first error
match try_join!(fallible_task1(), fallible_task2()) {
Ok((r1, r2)) => println!("Both succeeded: {}, {}", r1, r2),
Err(e) => println!("Error: {}", e),
}
}
// Timeout pattern
use tokio::time::{timeout, Duration};
async fn with_timeout() -> Result<String, String> {
match timeout(Duration::from_secs(5), slow_operation()).await {
Ok(result) => result,
Err(_) => Err("Timeout!".to_string()),
}
}
async fn slow_operation() -> Result<String, String> {
tokio::time::sleep(Duration::from_secs(10)).await;
Ok("Done".to_string())
}
Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.
Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.
Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.