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.
A program can distribute work across multiple cores: threads. The start is a function call with a closure:
use std::thread;
fn main() {
let daten = vec![1, 2, 3, 4];
let handle = thread::spawn(move || {
let summe: i32 = daten.iter().sum();
summe * 10
});
println!("Ergebnis: {}", handle.join().unwrap());
}
// → Ergebnis: 100
Three building blocks: spawn starts the closure on a new thread, move transfers the captured data as ownership (not as a borrow — the thread could outlive the creating scope, so any reference would dangle), and join() waits for the end and returns the result. If you forget join, main may end first — and the process takes the thread with it before it finished.
Why move is mandatory for threads
Check: What happens when main ends while a thread is still running?
Answer: The process ends — the thread is not executed to completion
Join is the agreement: you tell the program which work you want to wait for.
⚠ Common mistake: Leaving out the
movebefore the closure and misreading E0373 ("closure may outlive the current function, but it borrowsdaten…") as broken code — it means borrowed data does not belong in a thread that could outlive its creator. The compiler names the remedy right in its help hint: addmove, and the closure owns the data. Trying to rescue it with&goes in circles, because threads demand'static.
Takeaways:
The cleanest way to let threads exchange data: channels — a one-way street for messages. Go coined the phrase: "Do not communicate by sharing memory; share memory by communicating."
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for n in 1..=3 {
tx.send(n * n).unwrap();
}
drop(tx);
});
while let Ok(wert) = rx.recv() {
println!("{wert}");
}
}
// → 1
// 4
// 9
mpsc stands for: multiple producers, single consumer — many senders (clone the sender), one receiver. send transfers ownership of the message, recv waits blocking. And the end is anchored in the type: when all senders are lost, recv returns an Err — the while-let loop ends by itself. No polling, no magic values: the channel closing IS a value.
Check: Why does the while-let loop over rx.recv() end automatically when the sender is dropped?
Answer: recv then returns an Err — the channel is closed
Channel end is part of the type system: Err after the last sender. No polling needed.
⚠ Common mistake: Keeping the original sender in
mainwhile only clones go into the threads — the loop overrecv()never ends, because the channel closes only when the last sender is gone. The program hangs silently: no error, no panic. With thetx.clonepattern, drop the original sender deliberately or move it into a thread as well.
Takeaways:
Sometimes you don't want to copy or send data, but really share it. Then you need two parts: a locking mechanism and thread-safe ownership.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let zaehler = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let z = Arc::clone(&zaehler);
handles.push(thread::spawn(move || {
*z.lock().unwrap() += 10;
}));
}
for h in handles {
h.join().unwrap();
}
println!("Zähler: {}", *zaehler.lock().unwrap());
}
// → Zähler: 40
Mutex is the lock: lock() gives you a guard — only through it can you access the data, and when the guard is dropped, it releases the lock. Bypassing the lock is impossible, because the data is LOCKED INSIDE the Mutex. Arc is Rc with an atomic counter — the only reason the same structure can be shared across threads.
Together, they are the standard answer to "four threads, one counter" — and the compiler enforces the combination: it refuses Rc containers with E0277, and a Mutex without sharing would be pointless.
Fearless Concurrency in practice
Check: Why can't you just use Rc instead of Arc for thread-shared ownership?
Answer: Rc's reference counter is not atomic — data races at runtime
Rc uses a non-atomic reference counter. Concurrent clone calls from multiple threads would cause a data race. Arc uses atomic operations and is therefore Send + Sync.
⚠ Common mistake: Keeping the guard alive while a helper function locks the same mutex again — the thread then waits on itself: no compile error, no panic, just a perfect deadlock. Hold guards as briefly as possible, ideally in their own block around the access. With two mutexes, additionally agree on a fixed lock order.
Takeaways:
The finale: one million numbers, two cores, one answer. The scenario:
Scenario: The evaluation that takes forever
Check: Why does the parallel sum not need a Mutex?
Answer: Because each thread owns its own slice — no shared data
The threads share nothing — each owns its own slice (via move). When there is no shared data, no Mutex is needed. join() only collects the results; it does not protect shared data.
What you achieved in Module 12
⚠ Common mistake: Letting both threads write into the same accumulator variable (
sum += …in both closures) — the compiler refuses with E0499 ("cannot borrow as mutable more than once at a time"), and that is not spite but the data-race protection doing its job. That is why the solution computes separately and merges the partial results only afterjoin. Splitting the work instead of sharing the access often needs no lock at all.
Takeaways:
Course navigation: ← Module 11 · All 27 modules · Module 13 →