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 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.
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! β
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. π
lock,
change, then let go β and Arc<Mutex<T>> shares it across threads.
You've finished Doing Many Things at Once β amazing teamwork! π