Threads
Imagine you have a big list of tasks. Doing them all by yourself takes forever. But what if you had a helper who packed the bags while you sorted the gear? Two jobs happening at the same time! In Rust, those helpers are called threads. π§΅
Hiring a helper
To start a new thread, you call thread::spawn and hand it a little job to do.
The job goes inside || { ... }, which is just a tiny package of code.
When you spawn a helper, your main program keeps going too. So you need a way to
say βwait for my helper to finish before we stop.β Thatβs what .join() does.
Letβs spawn a thread
Here we hire a helper to print a message. Then we .join() to wait until the
helper is done before the program ends.
The helper.join() line makes the main program wait. Because we wait, the
helperβs message always prints first, then the thank-you. Nice and tidy! β
join, your main program might
finish and leave before the helper is done β like driving off without your friend! ππ¨
println! inside the helper's job?
Quick quiz
What does .join() do?
Yes! join tells the main program to wait until the helper is all done. π
thread::spawn(|| { ... }) starts one, and .join() waits for it
to finish. Next up: how threads send each other notes β Sending Notes (Channels)! π¨