×

c# · level 3 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.