C#: protecting shared state with lock

When two threads change the same variable without coordination, the result is unpredictable. counter++ is a read, an add, and a write, so interleaved threads can overwrite each other's updates. The part of the code that touches shared state is called the critical section.

C#
using System;
using System.Threading;

class Program {
  static int counter = 0;
  static readonly object gate = new object();

  static void Work() {
    for (int i = 0; i < 100000; i++) {
      lock (gate) {
        counter++;
      }
    }
  }

  static void Main() {
    var a = new Thread(Work);
    var b = new Thread(Work);
    a.Start();
    b.Start();
    a.Join();
    b.Join();
    Console.WriteLine("counter=" + counter);
  }
}
Read the full lesson