Concurrency
Thread-based concurrency with spawn/await, channels, and synchronization primitives.
How concurrency works in Turbo
Turbo uses OS threads for concurrency. spawn creates a new OS thread (via pthread_create), and await joins it (via pthread_join). There is no event loop, no green threads, and no non-blocking I/O runtime. Each spawned task is a real OS thread, so avoid spawning thousands of tasks -- each one consumes real system resources.
Async Functions
Declare functions with async fn to mark them as spawnable:
async fn compute(x: i64) -> i64 {
x * x + 1
}
fn main() {
let handle = spawn compute(5)
let result = await handle
print(result) // 26
}Spawn and Await
Use spawn to run a function on a new OS thread and await to block until it completes and get its result:
async fn fetch_data() -> i64 {
sleep(100)
42
}
fn main() {
let handle = spawn fetch_data()
// ... do other work while fetch_data runs on another thread ...
let result = await handle // blocks until the thread finishes
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 threads and collect results. Keep the thread count reasonable -- each spawn creates a real OS thread:
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
}