c# · level 3 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Threads that share a total need a .
Task.Run(() => ...) hands work to a from a shared pool: a separate worker running at the same time as your code. Four tills, four threads, real parallel work. And a new danger: total += 5 is three steps: read, add and write back.
Two threads can read the same old total, both add 5, and both write: one sale is lost. That is a , and the answer changes from run to run. Wrap the update in lock (gate) { ... }. Only one thread at a time may hold the lock on gate. The others wait.
using System;
using System.Linq;
using System.Threading.Tasks;
var gate = new object();
int total = 0;
var tills = Enumerable.Range(1, 4).Select(till => Task.Run(() =>
{
for (int sale = 0; sale < 10000; sale++)
{
lock (gate)
{
total += 5;
}
}
}));
await Task.WhenAll(tills);
Console.WriteLine($"Takings: {total}"); Without the lock, the takings would come out short, by a different amount each run.
guess first
Each task has its own slot. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Linq;
using System.Threading.Tasks;
int[] results = new int[3];
var work = Enumerable.Range(0, 3).Select(i => Task.Run(() =>
{
results[i] = (i + 1) * 100;
}));
await Task.WhenAll(work);
Console.WriteLine(string.Join(" ", results));
your turn
Your turn. Count the visitors safely.
On line 11, lock on the shared gate object, so only one turnstile at a time can add a visitor.
output
press run to see what happens
fix it
The savings jar will not compile. Can you fix it?
output
press run to see what happens
- C# says
intis not a reference type, as thelockstatement needs, on line 10. - A lock needs one object that every thread shares. A number gets copied, so it cannot be one.
- Add
var gate = new object();above line 5, changelock (pence)tolock (gate), then run.
nailed it
your threads can share safely now. :D
Task.Runhands work to another thread.total += 5is read, add, write, and threads can interleave.lockon one shared object lets one thread in at a time.
new words in your collection
- thread
- race condition
- lock
This lesson isn’t saved. A free account remembers every lesson you finish.