πŸ”
World 16 Β· Doing Many Things at Once

Sharing Safely (Mutex)

What if lots of helpers all want to change the same thing β€” like everyone adding their score to one scoreboard? If they all scribble at once, it’s a mess! Rust fixes this with a Mutex, which makes them take turns. πŸ”

The Big Idea A Mutex lets threads share one piece of data by taking turns: lock it, change it, then let go so the next helper can have a turn.

The talking stick

A Mutex works like a talking stick in a circle. Only the person holding the stick may speak β€” er, change the data. Everyone else waits politely for their turn.

  • .lock() means β€œgrab the talking stick.”
  • When you’re done, the stick is given up automatically so others can grab it.
Think of it like this… A talking stick πŸͺ„ makes sure only one person changes things at a time, so nobody talks over anybody and nothing gets garbled.

Sharing across threads

To share a Mutex with many threads, we wrap it in an Arc. Think of Arc as making safe copies of the same shared box so every helper can reach it.

Here, five helpers each add 1 to a counter. We wait for them all, then print the total.

Each helper grabs the lock, adds 1, then lets go. Because they take turns, no count is ever lost. Five helpers, five points β€” total is always 5! βœ…

Watch out! Without a Mutex, two helpers might change the number at the exact same moment and mess it up. The lock keeps everything safe and correct. πŸ›‘οΈ
Try this! Change 0..5 to 0..10 and press β–Ά Run. What total do you think it will print now?

Quick quiz

Why do threads use a Mutex?

Exactly! The Mutex is a talking stick β€” one turn at a time keeps the data correct. πŸ”

You learned… A Mutex lets threads share data by taking turns β€” lock, change, then let go β€” and Arc<Mutex<T>> shares it across threads. You've finished Doing Many Things at Once β€” amazing teamwork! πŸŽ‰