Synchronization in C#
Introduction of Synchronization- Synchronization is particularly important when threadsaccess the same data; it’s surprisingly easy to run aground in this area.
Synchronization constructs can be divided into four categories:- Simple blocking methods
- Locking constructs
- Signaling constructs
- No blocking synchronization constructs
Synchronization in Threads- Synchronization is needed in thread when we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time. using System; using System.Threading; namespace CSharpThreadExample
{ class Program { static void Main(string[] arg) { Console.WriteLine("-----> Multiple Threads ---->"); Printer p=new Printer(); Thread[] Threads=new Thread[3]; for(int i=0;i<3;i++) { Threads[i]=new Thread(new ThreadStart(p.PrintNumbers)); Threads[i].Name="Child "+i; } foreach(Thread t in Threads) t.Start();
Console.ReadLine(); } } class Printer { public void PrintNumbers() { for (int i = 0; i < 5; i++) { Thread.Sleep(100); Console.Write(i + ","); } Console.WriteLine(); } } }
|
Why we use Lock keyword- lock(object) is used to synchronize the shared object.
Syntax:
lock (objecttobelocked)
{
objecttobelocked.somemethod();
}
objecttobelocked is the object reference which is used by more than one thread to call the method on that object.
The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope.
Using of Monitor- The lock scope actually resolves to the Monitor class after being processed by the C# compiler. Lock keyword is just a notation for using System.Threading.Monitor class.
using System; using System.Threading; namespace CSharpThreadExample { class Program { static void Main(string[] arg) { Console.WriteLine(" -----> Multiple Threads ----->"); Printer p = new Printer(); Thread[] Threads = new Thread[3]; for (int i = 0; i < 3; i++) { Threads[i] = new Thread(new ThreadStart(p.PrintNumbers)); Threads[i].Name = "Child " + i; } foreach (Thread t in Threads) t.Start();
Console.ReadLine(); } } class Printer { public void PrintNumbers() { Monitor.Enter(this); try { for (int i = 0; i < 5; i++) { Thread.Sleep(100); Console.Write(i + ","); } Console.WriteLine(); } finally { Monitor.Exit(this); } } } }
|
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.