Open In App

C# – Lock in Thread

Last Updated : 28 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Multithreading is one of the powerful concepts of any programming language. It is basically thread-based multiprocessing. In this process, the program is divided into different parts and these parts are allowed to execute concurrently or simultaneously. The benefit of using multithreading in a program is that it maximizes the utilization of the CPU of our system. A thread is a lightweight sub-process that might share resources with another thread. That is why program using multithreading mechanism tends to consume less space. This varies with multitasking as in that case separate memory is allocated for different tasks. This article focuses upon demonstrating lock-in thread through C#. 

Lock in Thread

The lock statement is used to take the mutual-exclusion lock for a specified object. It executes a specified block and then releases the lock. The time during which the lock is active, the thread that holds the lock can again take and release the lock. Note that any other thread cannot access the lock and it waits unless the lock is released. 

Syntax:

lock (exp)

{

    // body

}

Here, exp is an expression of reference type.

Note: await operator cannot be used in the lock statement.

Example: In the below program, we are using a for-loop and at each step of the iteration, we are creating a new thread. Here, using the lock keyword we specify a statement block as a critical section by getting the mutual-exclusion lock for a specified object then executing a statement. Now the sleep() method has been used to pause the thread for a specific period of time then it will release the lock.

C#




// C# program to illustrate lock in thread
using System;
using System.Threading;
 
class GFG{
 
// Creating a reference type object
static readonly object obj = new object();
 
static void Sample()
{
     
      // Lock statement block
    lock(obj)
    {
         
          // Sleep the thread
        Thread.Sleep(20);
           
          // Print the count
        Console.WriteLine(Environment.TickCount);
    }
}
 
// Driver code
static public void Main()
{
     
      // Iterate using a for-loop
    for(int i = 0; i < 5; i++)
    {
         
          // Create a new thread
        ThreadStart begin = new ThreadStart(Sample);
           
          // Start executing the thread
        new Thread(begin).Start();
    }
}
}


 
 

Output:

 

-1836894307
-1836894283
-1836894263
-1836894243
-1836894223

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads