Concurrency and Source Panels
Lock Counter
Protect a shared counter while two threads increment it.
Lock Counter
LockCounter.cs
using System;
using System.Threading;
class Program
{
static readonly object Gate = new object();
static int counter;
static int rounds;
static void Increment()
{
for (int step = 0; step < rounds; step++)
{
lock (Gate)
{
int next = counter + 1;
counter = next;
}
}
}
static void Main()
{
int increments = ;
rounds = increments;
counter = 0;
Thread first = new Thread(Increment);
Thread second = new Thread(Increment);
first.Start();
second.Start();
first.Join();
second.Join();
Console.WriteLine($"increments={increments}");
Console.WriteLine($"counter={counter}");
}
}
using System;
using System.Threading;
class Program
{
static readonly object Gate = new object();
static int counter;
static int rounds;
static void Increment()
{
for (int step = 0; step < rounds; step++)
{
lock (Gate)
{
int next = counter + 1;
counter = next;
}
}
}
static void Main()
{
int increments = ;
rounds = increments;
counter = 0;
Thread first = new Thread(Increment);
Thread second = new Thread(Increment);
first.Start();
second.Start();
first.Join();
second.Join();
Console.WriteLine($"increments={increments}");
Console.WriteLine($"counter={counter}");
}
}
using System;
using System.Threading;
class Program
{
static readonly object Gate = new object();
static int counter;
static int rounds;
static void Increment()
{
for (int step = 0; step < rounds; step++)
{
lock (Gate)
{
int next = counter + 1;
counter = next;
}
}
}
static void Main()
{
int increments = ;
rounds = increments;
counter = 0;
Thread first = new Thread(Increment);
Thread second = new Thread(Increment);
first.Start();
second.Start();
first.Join();
second.Join();
Console.WriteLine($"increments={increments}");
Console.WriteLine($"counter={counter}");
}
}
lock
A `lock` block lets only one thread update the guarded state at a time.