C# program to demonstrate thread lock

Threading lock in C#: Here, we are going to learn how to lock a thread in C#?
Submitted by Nidhi, on August 16, 2020

To solve the above problem, here we will implement a mutual-exclusion lock to resolve the problem of the critical section. Here we block a critical section (set of statements) and execute statements and then release the lock.

Program:

/*
 *  Demonstrate thread lock using C# program
 */
 
using System;
using System.Threading;
 
class LockDemo
{
    static readonly object _object = new object();
 
    static void ThreadMethod()
    {
        lock (_object)
        {
            Thread.Sleep(100);
            Console.WriteLine(DateTime.Now);
        }
    }
    static void Main()
    {
        int loop = 0;

        while (loop < 5)
        {
            ThreadStart T = new ThreadStart(ThreadMethod);
            new Thread(T).Start();
            loop++;
        }
    }
}

Output:

8/13/2020 8:14:54 PM
8/13/2020 8:14:54 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
Press any key to continue . . .

Explanation:

In the above program, we created a LockDemo class that contains two static methods ThreadMethod() and Main(). In the ThreadMethod(), we used mutual exclusive lock using lock keyword and Thread.Sleep() method is used to pause the thread execution. In the Main() method we created threads in the while loop.

C# Thread Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.