Hard csharp

Thread — parallel counter

Problem

Start two threads incrementing a shared counter (demo with lock).

Hints
  • lock object when updating shared counter

Your practice code

Ready — edit the code above and click Run.

Solution

using System;
using System.Threading;

class Program {
    static int counter = 0;
    static object gate = new();
    static void Main() {
        var t1 = new Thread(() => { lock (gate) { counter++; } });
        var t2 = new Thread(() => { lock (gate) { counter++; } });
        t1.Start(); t2.Start();
        t1.Join(); t2.Join();
        Console.WriteLine(counter);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Race conditions without sync—use lock or Interlocked. Modern code prefers Task/async.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details