C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Synchronization: The key to synchronization is the concept of lock


Posted Date: 23 May 2004    Resource Type: Articles    Category: .NET Framework
Author: ANITA MARY JOSEPHMember Level: Gold    
Rating: 1 out of 5Points: 7



When using Multiple threads, it is sometimes necessary for a program to coordinate the activities of two or more of the threads. The process by which this is achieved is called synchronization. The most common reason for using synchronization is when two or more threads need access to a shared resource that can be used by only one thread at a time.

Key to synchronization is the concept of lock, which controls access to a block of code within an object. When an object is locked by one thread, no other thread can gain access to the locked block of code. When the thread releases the lock, the object is available for use by another thread.

Synchronization is supported by the keyword lock.
The general form of lock is shown here:

lock(object)
{
//statements to be synchronized.
}

Here, object is a reference to the object being synchronized. If you want to synchronize a single statement, the curly braces are not needed. A lock statement ensures that the section of code protected by the lock for the given object can be used only by the thread that obtains the lock. All other threads are blocked until the lock is removed. The lock is released when the block is exited.

Example:

//Using lock to synchronize access to an object.

using System;
using System.Threading;

class SumArray
{
int sum;
public int SumIt(int[] number)
{
lock(this)
{
// lock the entire method
sum = 0; // reset sum
for(int i = 0; i < number.Length; i++)
{
sum += number[i];
Console.WriteLine("Running total for " + Thread.CurrentThread.Name + " is " + sum);
Thread.Sleep(20); // allow task-switch
}
return sum;
}
}
}
class MyThread
{
public Thread thread;
int[] anumber;
int answer;

static SumArray sumArray = new SumArray();
public MyThread(string name, int[] number)
{
anumber = number;
thread = new Thread(new ThreadStart(this.run));
thread.Name = name;
thread.Start(); //start the thread
}

//Entry point of thread.
void run()
{
Console.WriteLine(thread.Name + " starting.");
answer = sumArray.SumIt(anumber);
Console.WriteLine("Sum for " + thread.Name + " is " +answer);
Console.WriteLine(thread.Name + " terminating. ");
}
}
class Synchronize
{
public static void Main()
{
int[] anumber = {1, 2, 3, 4, 5};

MyThread myThread1 = new MyThread("Child #1", anumber);
MyThread myThread2 = new MyThread("Child #2", anumber);

myThread1.thread.Join();
myThread2.thread.Join();
Console.Read();
}
}


The effects of lock are summarized here:

1. For any given object, once a lock has been placed on a section of code, the object is locked and no other thread can acquire the lock.

2. Other threads trying to acquire the lock on the same object will enter a wait state until the code is unlocked.

3. When a thread leaves the locked block, the object is unlocked. One other thing to understand about lock is that it should be used only on objects that are either private or internal. If this is not the case, then some thread external to your program could obtain a lock and not release it.


Locking a Static Method
Since lock works with an object, you might at first think that you can’t lock code within a static method since there is no object to lock on. However, this is wrong. To lock a static method, use the following form of lock:

lock(typeof(class))
{
//locked block
}
Here, class is the name of the class that contains the static method.



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: XML serialization and Binary serialization
Previous Resource: How to populate a TreeView control from an Access database....!
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use