Lock and Monitor

Learn about the most common ways to synchronize threads.

We'll cover the following

Introduction

The basic principles behind different thread synchronization mechanisms are almost the same. Whenever a thread will use a shared resource (and thus enter the critical section), it locks it. If two threads are to use the same shared resource, one of them waits while the other one works with it.

The lock keyword

The most straightforward way to achieve our synchronization objectives is to enclose the critical section of our code within a lock block. We have to use some dummy object as a locker:

static object locker = new object();

static void SomeMethod()
{
    lock(locker)
    {
        // Critical section
    }
}

The locker variable is an arbitrary dummy object that the lock statement uses to gain exclusive access to the critical section. When a thread reaches the lock statement, it first checks whether the locker is free. If not, it waits until the locker is released.

Let’s see if this approach solves the problem with a shared resource access:

Get hands-on with 1200+ tech skills courses.