🧡
World 16 Β· Doing Many Things at Once

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. 🧡

The Big Idea A thread is a helper that runs part of your program at the same time as the rest. With threads, your program can do more than one thing at once.

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.

Think of it like this… You send a friend to grab a book from the library. join is you waiting at the door until they get back, so nobody leaves without the book. πŸ“š

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! βœ…

Ferris says: If you forget to join, your main program might finish and leave before the helper is done β€” like driving off without your friend! πŸš—πŸ’¨
Try this! Change the helper's message to something funny, then press β–Ά Run. Can you add a second 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. πŸŽ‰

You learned… A thread is a helper that runs at the same time as your program. thread::spawn(|| { ... }) starts one, and .join() waits for it to finish. Next up: how threads send each other notes β€” Sending Notes (Channels)! πŸ“¨