SYNCHRONIZATION.
Ø
Synchronization is particularly important when threads access 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();
}
}
}
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);
}
}
}
}
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.