Async & Concurrency
Real async/await with thread-based concurrency, channels, and synchronization primitives.
Async Functions
Declare asynchronous functions with async fn:
async fn compute(x: i64) -> i64 {
x * x + 1
}
async fn main() {
let result = await compute(5)
print(result) // 26
}Spawn and Await
Use spawn to run a function concurrently and await to wait for its result:
async fn fetch_data() -> i64 {
sleep(100)
42
}
fn main() {
let handle = spawn fetch_data()
// ... do other work while fetch_data runs ...
let result = await handle
print(result) // 42
}Channels
Channels provide message passing between concurrent tasks:
fn producer(ch: i64) {
for i in 0..5 {
send(ch, i * 10)
}
}
fn main() {
let ch = channel()
spawn producer(ch)
let mut i = 0
while i < 5 {
let val = recv(ch)
print(val) // 0, 10, 20, 30, 40
i += 1
}
}Mutex
Protect shared state with mutex primitives:
fn main() {
let m = mutex(0)
// Read the value
let val = mutex_get(m)
print(val) // 0
// Update the value
mutex_set(m, 42)
print(mutex_get(m)) // 42
}Sleep
Pause execution for a given number of milliseconds:
async fn delayed_greeting() -> str {
sleep(1000) // wait 1 second
"Hello after delay!"
}
fn main() {
let handle = spawn delayed_greeting()
print("Waiting...")
let msg = await handle
print(msg)
}Concurrent Patterns
Spawn multiple tasks and collect results:
async fn compute_square(x: i64) -> i64 {
x * x
}
fn main() {
// Spawn multiple concurrent tasks
let h1 = spawn compute_square(10)
let h2 = spawn compute_square(20)
let h3 = spawn compute_square(30)
// Await all results
let a = await h1
let b = await h2
let c = await h3
print(a + b + c) // 100 + 400 + 900 = 1400
}