Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Imagine your server needs to handle 10,000 concurrent connections. With synchronous threads, you need 10,000 OS threads — this is not scalable:
Async I/O solves this problem through non-blocking operations:
// Synchronous: blocks the thread
let data = file.read().unwrap(); // Thread waits here
// Asynchronous: returns control
let data = file.read().await; // Thread can process other tasks
Async ≠ Parallel
Asynchronous means: an operation yields the thread while waiting for something external (I/O, timers). Parallel means: executing multiple things at the same time (multi-core).
Async is cooperative multitasking: tasks voluntarily yield the CPU. Parallel is preemptive multitasking: the OS takes CPU from tasks.
Both can be combined: async tasks on multiple threads.
Rust uses Futures and async/await:
async fn defines an async function.await waits for a Future's resultCheck: What is the main advantage of Async I/O?
Answer: A single thread can handle many connections simultaneously
Async enables a thread to manage thousands of I/O operations simultaneously without blocking. Performance gains come from reduced context switches.
Takeaways:
⚠ Common mistake: Equating async and parallel programming — async solves I/O blocking without additional threads, while parallelism requires actual concurrency across multiple cores.
A Future is a value that will (possibly) be ready at some point. It is lazy: nothing happens until you actively wait for it.
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> {
Ready(T), // Result is ready
Pending, // Not ready yet
}
// → Ready(T) signals completion, Pending that the Future is not ready yet
poll() is called repeatedlyPending: the task is stored to be woken up laterReady(T): the result is availableFutures are Lazy
A Future does nothing when you just create it. You need an executor that polls the Future and drives it to completion.
// This code does nothing - no executor!
let future = async {
println!("I will never execute!");
};
let future = async {
// This code runs when the Future is polled
let result = some_async_operation().await;
result + 1
};
async fn fetch_data() -> Result<String, Error> {
let client = reqwest::Client::new();
let response = client.get("https://api.example.com").send().await?;
response.text().await
}
The futures crate provides helpers for combining:
use futures::future;
async fn fetch_all() -> Vec<String> {
let future1 = fetch_url("https://api1.com");
let future2 = fetch_url("https://api2.com");
// Execute both Futures in parallel
let (result1, result2) = future::join(future1, future2).await;
vec![result1, result2]
}
Scenario: The three APIs
Takeaways:
⚠ Common mistake: Creating a Future but never executing it with an executor — the code in the async block will never run, even though it is syntactically correct.
async fn my_async_function(param: u32) -> String {
// Body is a Future
format!("Result: {}", param)
}
impl Future<Output = T>fn → async fnasync fn example() {
let result1 = first_operation().await;
let result2 = second_operation(result1).await;
println!("Results: {}, {}", result1, result2);
}
.await does not block the thread.await vs .unwrap()
.unwrap(): Panic if Result/Option is Err/None — synchronous.await: Wait for Future — asynchronous, yields thread// ❌ Wrong: would block
let result = future.unwrap();
// ✅ Correct: async wait
let result = future.await;
let future = async {
let x = operation1().await;
let y = operation2().await;
x + y // Last expression = Future output
};
async fn fetch() -> Result<String, Error> {
let response = reqwest::get("https://api.example.com").await?;
let text = response.text().await?;
Ok(text)
}
? works with .await tooResult<Future, Error>Check: What does
.awaitdo to a Future?Answer: It pauses the task and yields control back until the Future is ready
.await is non-blocking: the executor can run other tasks while the Future waits for a result. The thread is freed, not blocked.
Takeaways:
⚠ Common mistake: Using
.unwrap()on a Future instead of.await— this causes a compile error because Futures cannot be directly unwrapped and require an executor context.
Futures do nothing until an executor polls them and drives them forward.
The de-facto standard for async Rust:
#[tokio::main]
async fn main() {
let result = my_async_function().await;
println!("{}", result);
}
The #[tokio::main] macro:
Alternative runtime:
#[async_std::main]
async fn main() {
let result = my_async_function().await;
println!("{}", result);
}
use futures::executor::block_on;
fn main() {
let future = async {
println!("Running...");
42
};
let result = block_on(future);
println!("Result: {}", result);
}
Warning: block_on blocks the current thread! Only for tests and simple cases.
Runtime Selection
Choose your runtime based on requirements:
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
// Runs on a worker thread
"Hello from Tokio"
});
let result = handle.await.unwrap();
println!("{}", result);
}
use std::time::Duration;
#[tokio::main]
async fn main() {
let result = tokio::time::timeout(
Duration::from_secs(5),
long_operation()
).await;
match result {
Ok(value) => println!("Done: {}", value),
Err(_) => println!("Timeout!"),
}
}
Takeaways:
⚠ Common mistake: Using
tokio::spawnwithout#[tokio::main]or a running runtime — this causes a panic because there is no executor to run the tasks.
Runs several futures concurrently and waits for all of them:
#[tokio::main]
async fn main() {
let (result1, result2, result3) = tokio::join! {
fetch_data("url1"),
fetch_data("url2"),
fetch_data("url3"),
};
println!("Results: {}, {}, {}", result1, result2, result3);
}
For dynamic lists of futures:
use futures::future;
#[tokio::main]
async fn main() {
let urls = vec!["url1", "url2", "url3"];
let futures: Vec<_> = urls.into_iter()
.map(|url| fetch_data(url))
.collect();
let results = future::join_all(futures).await;
for result in results {
println!("Got: {}", result);
}
}
use tokio::sync::oneshot;
#[tokio::main]
async fn main() {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
tokio::spawn(async {
tokio::time::sleep(Duration::from_secs(1)).await;
tx1.send("Slow").unwrap();
});
tokio::spawn(async {
tokio::time::sleep(Duration::from_millis(100)).await;
tx2.send("Fast").unwrap();
});
tokio::select! {
result = rx1 => {
println!("rx1 finished first: {:?}", result);
}
result = rx2 => {
println!("rx2 finished first: {:?}", result);
}
}
}
Cooperative vs Preemptive Scheduling
Tokio uses cooperative scheduling:
.await so other tasks can runCompared with OS threads:
.awaitTokio uses work stealing for load balancing:
Check: What is the difference between
tokio::spawnand.await?Answer: spawn starts a task in the background, await waits in place
spawn detaches the task — it runs in the background. await waits on the spot for the result. Both need a running executor (e.g. #[tokio::main]).
Takeaways:
⚠ Common mistake: Using
tokio::select!with futures that never complete — this causes a deadlock as select! waits for one of the futures and the others never finish.
A Stream is a future that produces several values over time.
pub trait Stream {
type Item;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>
) -> Poll<Option<Self::Item>>;
}
Option<Item>None signals the end of the streamSome(item) produces the next valueuse futures::stream::{self, StreamExt};
#[tokio::main]
async fn main() {
let stream = stream::iter(vec![1, 2, 3, 4, 5]);
let sum = stream
.filter(|x| *x % 2 == 0) // Only even numbers
.fold(0, |acc, x| acc + x)
.await;
println!("Sum of even numbers: {}", sum);
}
async fn generate_numbers() -> impl Stream<Item = i32> {
futures::stream::iter(0..10)
.map(|i| async move {
tokio::time::sleep(Duration::from_millis(100)).await;
i * 2
})
.buffer_unordered(5) // At most 5 futures at once
}
#[tokio::main]
async fn main() {
let mut stream = generate_data();
while let Some(item) = stream.next().await {
println!("Received: {}", item);
}
}
use futures::stream;
#[tokio::main]
async fn main() {
let stream1 = stream::iter(1..=3);
let stream2 = stream::iter(4..=6);
// Merge two streams (alternating)
let merged = stream::select(stream1, stream2);
// Or: first stream1, then stream2
let chained = stream1.chain(stream2);
}
Backpressure
Streams can handle backpressure automatically:
// Without backpressure: producer could flood the consumer
let stream = stream::iter(0..1000000);
// With backpressure: the producer waits on the consumer
let processed = stream
.map(|x| async move { /* slow processing */ x * 2 })
.buffer_unordered(100); // At most 100 in flight
Takeaways:
⚠ Common mistake: Using
buffer_unorderedwithout a limit — this can cause memory overflow with many parallel futures as all are started simultaneously and wait for their results.
In synchronous code:
let mut data = vec![1, 2, 3];
// ... can mutate freely
In async code: data could be accessed by several tasks at once → Data Race
use tokio::sync::Mutex;
#[tokio::main]
async fn main() {
let shared_data = Mutex::new(Vec::new());
let handle1 = tokio::spawn(async move {
let mut guard = shared_data.lock().await;
guard.push(1);
});
let handle2 = tokio::spawn(async move {
let mut guard = shared_data.lock().await;
guard.push(2);
});
handle1.await.unwrap();
handle2.await.unwrap();
let data = shared_data.lock().await;
println!("Data: {:?}", *data); // [1, 2] or [2, 1]
// → [1, 2] or [2, 1] depending on scheduling order
}
Mutex::lock() is async — it frees the thread while waitinguse tokio::sync::RwLock;
#[tokio::main]
async fn main() {
let data = RwLock::new(42);
// Multiple readers at once
let handle1 = tokio::spawn(async move {
let guard = data.read().await;
println!("Reader 1: {}", *guard);
});
let handle2 = tokio::spawn(async move {
let guard = data.read().await;
println!("Reader 2: {}", *guard);
});
// Exclusive writer
let handle3 = tokio::spawn(async move {
let mut guard = data.write().await;
*guard = 100;
});
handle1.await.unwrap();
handle2.await.unwrap();
handle3.await.unwrap();
}
use std::sync::Arc;
use tokio::sync::Mutex;
#[tokio::main]
async fn main() {
// Arc for shared ownership
let shared = Arc::new(Mutex::new(0));
let shared_clone = Arc::clone(&shared);
let handle = tokio::spawn(async move {
let mut guard = shared_clone.lock().await;
*guard += 1;
});
handle.await.unwrap();
let guard = shared.lock().await;
println!("Count: {}", *guard);
}
Arc + Mutex vs Arc + RwLock
Arc<Mutex<T>>: Exclusive access, good for frequent write operationsArc<RwLock<T>>: Multiple readers, one writer, good for read-heavy workloadsBoth are async-aware in Tokio.
Takeaways:
⚠ Common mistake: Using the standard
std::sync::Mutexinstead oftokio::sync::Mutexin async code — the synchronous mutex blocks the thread while waiting, which blocks the entire async runtime.
Course navigation: ← Module 16 · All 27 modules · Module 18 →