
I Thought I Understood Threads. Then I Read Atomics and Locks.
Let me paint a picture. You're writing a Rust program. It starts, runs top to bottom, and exits. One thread. One lane of traffic. Fine — until you want two things to happen at the same time . Maybe you want to download a file while showing a progress bar. Maybe you're writing a server that needs to handle multiple requests. Maybe you just want to go fast. That's when threads enter the picture. And that's when most languages say "good luck" and hand you a loaded footgun. Rust does something different. Starting a Thread is Stupidly Simple use std :: thread ; fn main () { thread :: spawn ( f ); thread :: spawn ( f ); println! ( "Hello from the main thread." ); } fn f () { println! ( "Hello from another thread!" ); let id = thread :: current () .id (); println! ( "This is my thread id: {id:?}" ); } std::thread::spawn takes a function, hands it to a new thread, and gets out of the way. That's it. But here's the first gotcha: if main() returns, the whole program dies — even if other threads
Continue reading on Dev.to
Opens in a new tab
