This article explains what Thread Locking is and how to use it efficiently in multithreading environment.
- Threading Simplified: Part 1 (Threads Inception)
- Threading Simplified: Part 2 (Multithreading Concepts)
- Threading Simplified: Part 3 (Threads type)
- Threading Simplified: Part 4 (Threads Creation)
- Threading Simplified: Part 5 (Thread Pools)
- Threading Simplified: Part 6 (Exception Handling)
- Threading Simplified: Part 7 (Thread Priority)
- Threading Simplified: Part 8 (Synchronization Basics and Thread Blocking)
Thread Locking, lock keyword
I am again here to continue the discussion around Threading. Today, we will discuss about Thread Locking and related concepts.
Let’s start by putting questions to understand the concepts.
Why Thread Locking?
Locking is used to ensure that only one thread can enter at a time in a code block.
Is Locking Thread Safe by default?
Locking is not thread safe by default and one needs to handle it explicitly to avoid thread clash in a multithreaded environment.
Good so far. Let’s understand it bya simple example.
- class TestThreadSafe
- {
- int num1 = 0;
- int num2 = 0;
- Random rnd = new Random();
- public void DoDivide()
- {
- for(inti = 0; i < 1000000; i++)
- {
- num1 = rnd.Next(1, 5);
- num2 = rnd.Next(1, 5);
- Console.WriteLine(num1 / num2);
- num1 = 0;
- num2 = 0;
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Console.Title = "Thread Locking Demo";
- TestThreadSafe testThreadSafe = new TestThreadSafe();
- Threadt1 = new Thread(testThreadSafe.DoDivide);
- Threadt2 = new Thread(testThreadSafe.DoDivide);
- t1.Start();
- t2.Start();
- }
- }



Prakash TripathiPosted Mar 7, 2016, 12:16 PM
Thnx Ankur.
Ankur MistryPosted Mar 7, 2016, 12:16 PM
Very nice Prakash Tripathi
Prakash TripathiPosted Mar 7, 2016, 7:40 AM
Thnx Sibeesh.
Sibeesh VenuPosted Mar 7, 2016, 7:29 AM
Nice Share
Prakash TripathiPosted Mar 7, 2016, 6:27 AM
Thnx Vignesh.
Vignesh ManiPosted Mar 7, 2016, 6:08 AM
Good
Prakash TripathiPosted Mar 7, 2016, 4:23 AM
Thnx Ibrahim.
Mohammed IbrahimPosted Mar 7, 2016, 4:11 AM
nice
Prakash TripathiPosted Mar 7, 2016, 2:06 AM
Welcome Sonu.
Sonu ChaudharyPosted Mar 7, 2016, 1:17 AM
thanks
Prakash TripathiPosted Mar 7, 2016, 12:54 AM
Thnx Asfend.
Asfend YarPosted Mar 7, 2016, 12:47 AM
nice
Prakash TripathiPosted Mar 6, 2016, 10:57 PM
Thnx Humayun.
Humayun Kabir MamunPosted Mar 6, 2016, 10:41 PM
Nice...
Prakash TripathiPosted Mar 6, 2016, 9:47 PM
Thnx Kumaresh
Prakash TripathiPosted Mar 6, 2016, 9:47 PM
Thnx Karthiga.
Prakash TripathiPosted Mar 6, 2016, 9:46 PM
Thnx Asfend.
Kumaresh RajalingamPosted Mar 6, 2016, 8:29 PM
good one
Kumaresh RajalingamPosted Mar 6, 2016, 8:29 PM
Nice explanation
Sr KarthigaPosted Mar 6, 2016, 8:17 PM
god one
Sr KarthigaPosted Mar 6, 2016, 8:17 PM
Nice explanation
Asfend YarPosted Mar 6, 2016, 2:58 PM
nice