Interlocked vs Lock in CSharp

Here is an article that explains the differences between Interlocked and Lock in C#, along with various code examples demonstrating their usage in different scenarios.


Understanding Interlocked and Lock in C#

In multithreaded programming, both Interlocked and Lock are used for thread synchronization, but they serve different purposes. This article delves into the differences between Interlocked and Lock in C#, providing detailed code examples for various use cases.

Interlocked for Atomic Operations

Interlocked ensures atomic operations, as shown in the following example:

using System;
using System.Threading;

class Program
{
    static int sharedValue = 0;

    static void Main()
    {
        var threads = new Thread[5];

        for (int i = 0; i < 5; i++)
        {
            threads[i] = new Thread(IncrementValue);
            threads[i].Start();
        }

        foreach (var thread in threads)
        {
            thread.Join();
        }

        Console.WriteLine("Shared Value: " + sharedValue);
    }

    static void IncrementValue()
    {
        for (int i = 0; i < 100000; i++)
        {
            Interlocked.Increment(ref sharedValue);
        }
    }
}

Lock for Critical Sections

Lock is used for protecting critical sections of code, ensuring exclusive access for threads, as shown in the example below:

using System;
using System.Threading;

class Program
{
    static int sharedValue = 0;
    static object lockObject = new object();

    static void Main()
    {
        var threads = new Thread[5];

        for (int i = 0; i < 5; i++)
        {
            threads[i] = new Thread(IncrementValue);
            threads[i].Start();
        }

        foreach (var thread in threads)
        {
            thread.Join();
        }

        Console.WriteLine("Shared Value: " + sharedValue);
    }

    static void IncrementValue()
    {
        for (int i = 0; i < 100000; i++)
        {
            lock (lockObject)
            {
                sharedValue++;
            }
        }
    }
}

Understanding the differences between Interlocked and Lock is crucial for effective thread synchronization in C#. By utilizing these constructs appropriately, developers can ensure efficient and thread-safe execution of critical sections in multithreaded environ