Locking one thread until the contended resources are available

There are instances where we want to give sole access to a process to a specific thread. We can do this using the lock keyword. This will execute this process in a thread-safe manner. Therefore, when a thread runs the process, it will gain exclusive access to the process for the duration of the lock scope. If another thread tries to gain access to the process inside the locked code, it will be blocked and have to wait its turn until the lock is released.

Getting ready

For this example, we will use tasks. Make sure that you have added the using System.Threading.Tasks; statement to the top of your Recipes class.

How to do it…

  1. In the Recipes class, add an object called threadLock with the private modifier. Then, add two methods called LockThreadExample() and ContendedResource() that take an integer of seconds to sleep as a parameter:
    public class Recipes
    {
        private object threadLock = new object();
        public void LockThreadExample()
        {        
    
        }
    
        private void ContendedResource(int sleepSeconds)
        {        
    
        }
    }

    Note

    It is considered a best practice to define the object to lock on as private.

  2. Add three tasks to the LockThreadExample() method. They will create threads that try to access the same section of code simultaneously. This code will wait until all the threads have completed before terminating the application:
    Task thread1 = Task.Factory.StartNew(() => ContendedResource(3));
    Task thread2 = Task.Factory.StartNew(() => ContendedResource(5));
    Task thread3 = Task.Factory.StartNew(() => ContendedResource(2));
    
    Task.WaitAll(thread1, thread2, thread3);
    WriteLine("All tasks completed");
  3. In the ContendedResource() method, create a lock using the private threadLock object and then make the thread sleep for the amount of seconds passed to the method as a parameter:
    int threadID = Thread.CurrentThread.ManagedThreadId;
    lock (threadLock)
    {
        WriteLine($"Locked for thread {threadID}");
        Thread.Sleep(sleepSeconds * 1000);
    }
    WriteLine($"Lock released for thread {threadID}");
  4. Back in the console application, add the following code to instantiate a new Recipes class and call the LockThreadExample() method:
    Chapter7.Recipes oRecipe = new Chapter7.Recipes();
    oRecipe.LockThreadExample();
    Console.ReadLine();
  5. Run the console application and see the information output to the console window:
    How to do it…

How it works…

We can see that thread 11 gained exclusive access to the contended resource. At the same time, thread 11 and thread 12 tried to access the contended resource locked by thread 11. This then caused the other two threads to wait until thread 11 had completed and released the lock. The result of this is that the code is executed in an orderly manner, as can be seen in the console window output. Each thread waits its turn until it can access the resource and lock its thread.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.197