C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Implementing ReaderWriterLock for seamless Read and Write Operations


Posted Date: 20 Mar 2007    Resource Type: Code Snippets    Category: Threading

Posted By: Balamurali Balaji       Member Level: Diamond
Rating:     Points: 10



In a multi-threaded environment, suppose an object is shared by multiple read and a single write requests, to avoid concurrency problems (dead-lock situations), ReaderWriterLock class is used. It has AcquireReaderLock and ReleaseReaderLock methods to make a read request on a shared object. Similarly, for write operations we can use the AcquireWriterLock and ReleaseWriterLock methods.

The following code shows how to use a list object shared by both read and write operations performed on separate threads. When the write thread adds a random integer item to the list, read thread is not stopped or waited. Instead, it continues to read the values from the list. Just by obtaining the lock and releasing the lock during the read write operations enable the seamless output from both the threads.



static ReaderWriterLock rw = new ReaderWriterLock();
static List items = new List();

static void Main(string[] args)
{
new Thread(delegate() { while (items.Count <= 100) AppendItem(); }).Start();
new Thread(delegate() { while (items.Count <= 100) WriteTotal(); }).Start();
new Thread(delegate() { while (items.Count <= 100) WriteTotal(); }).Start();
}

static void WriteTotal()
{
rw.AcquireReaderLock(10000);
int tot = 0; foreach (int i in items) tot += i;
Console.WriteLine(tot);
rw.ReleaseReaderLock();
}

static void AppendItem()
{
rw.AcquireWriterLock(10000);
items.Add((new Random()).Next(10));
Thread.Sleep(500);
rw.ReleaseWriterLock();
}





Responses


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

Feedbacks      
Popular Tags   What are tags ?   Search 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.
Previous Resource: Prevent sharing of static fields across instances/threads
Return to Discussion Resource Index
Post New Resource
Category: Threading


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

conference calls

Contact Us    Privacy Policy    Terms Of Use