Solved

816161 and/or ReaderWriterLock thread example help.

Posted on 2004-08-16
9
335 Views
Last Modified: 2010-04-15
First off, forget my lack of full understanding of thread locking.  Please do not suggest the C# LOCK method, I am aware of this feature.  I am trying to understand the ReaderWriterLock methods available.  The Microsoft Support article 816161 This just does not look right to me.  What am I missing?  Here is the suggestioned ReaderWriterLock example.

namespace MultiThreadApplication
{
  class Class1
  {
    private ReaderWriterLock rwl = new ReaderWriterLock();
    private int myNumber;
    public int Number   // the Number property
    {
      get
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        try
        {
          Thread.Sleep(50);  //What is this doing here?
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return myNumber;
      }
      set
      {
        rwl.AcquireWriterLock(Timeout.Infinite);
        try
        {
          Thread.Sleep(50);     // again with the sleeping!!??
          myNumber = value;
        }
        finally
        {
          rwl.ReleaseWriterLock();
        }      }    }  }}  // So I don't take endless pages on EE

0
Comment
Question by:ErikPhilips
  • 5
  • 4
9 Comments
 
LVL 4

Author Comment

by:ErikPhilips
ID: 11807828
Alright, I could be way off, but with the above example, the lock is released before the return?  Isn't it theoretically possible (especially on a multiple processor machine) for a write to occur between the ReleaseReaderLock and the return mynumber, however unprobable?  Could less error prone code look like the following?  Or am I completely whacked, and I am just not getting it? :)

namespace MultiThreadApplication
{
  class Class1
  {
    private ReaderWriterLock rwl = new ReaderWriterLock();
    private int myNumber;
    public int Number   // the Number property
    {
      get
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        try
        {
          int result = myNumber;          
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return result;
      }
      set
      {
        rwl.AcquireWriterLock(Timeout.Infinite);
        try
        {
          myNumber = value;
        }
        finally
        {
          rwl.ReleaseWriterLock();
        }      }    }  }}  // :)
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 11808144
finally block is executed in any case: both if exception occured or not. Lock is released always.
Thread.Sleep is used for testing purposes - if you want to write multi-threaded application which uses this class, you need to test this class for thread safety. However, without Sleep get and set methods time is so short that program is working correctly also without  ReaderWriterLock. Real program may execute some processing in the code fragment protected by ReaderWriterLock, for example, read/write some array. Sleep emulates such situation.

Write may occur after release of ReleaseReaderLock and returning the result. But this is OK, get method returns value which is valid at the time of get call. After get call value may be changed by writer.

0
 
LVL 48

Expert Comment

by:AlexFM
ID: 11808170
AcquireReaderLock and AcquireWriterLock are used with Timeout.Infinite parameter. If some thread calls AcquireWriterLock and doesn't call ReleaseWriterLock, any other thread which calls AcquireWriterLock is locked. The only way to exit from deadlock is to call Thread.Abort, whicha caused exception in currently executed code. This is a reason of using try block in this code fragment.
0
 
LVL 4

Author Comment

by:ErikPhilips
ID: 11808210
I completely understand making sure the Lock is always released.  Bad things have... could have happend if I did't do that. :)

I also understand the infinite wait period.  I may not have asked my question to the proper detail.

the MS Example looks like to me is it acquires a reader lock, the releases it, then returns the value mynumber.  Where as what my Example looks like is acquire a lock, read the value into local variable, release the lock, return the local variable.  It appears my would leave no room for a write/read error.  Is this correct?

 get  //MS Example
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        try
        {
          Thread.Sleep(50);
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return myNumber;

 get // my Example
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        try
        {
          int result = myNumber;          
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return result;
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 48

Accepted Solution

by:
AlexFM earned 250 total points
ID: 11808312
Yes, your code is correct. When I answered your question, I didn't pay attention to the difference between your and MS code.
0
 
LVL 4

Author Comment

by:ErikPhilips
ID: 11808321
BAD MS!!!
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 11808334
"Write may occur after release of ReleaseReaderLock and returning the result. But this is OK, get method returns value which is valid at the time of get call. After get call value may be changed by writer."

This was written reading your code:

      get
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        try
        {
          int result = myNumber;          
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return result;
      }

and not MS code from the first post. MS code is wrong.
0
 
LVL 4

Author Comment

by:ErikPhilips
ID: 11808357
I understand what you are saying, but sometimes it may not be the value I was expecting.  After all, if 4 threads have read locks, and a 5th is waiting on a writelock, and I need those 4 threads to have the same value on the last read before the write, the MS code example may not follow that rule.
0
 
LVL 4

Author Comment

by:ErikPhilips
ID: 11818241
Wait a sec, my code doesn't WORK!!!  What the...

MultiThreadApplication.cs(33): The name 'result' does not exist in the class or namespace MultiThreadApplication.Class1

hahaha  I didn't know when you scoped varibles, that it would actually scope the variable "INSIDE" the try statement... the following works

      get
      {
        rwl.AcquireReaderLock(Timeout.Infinite);                
        int result;
        try
        {
          result = myNumber;          
        }
        finally
        {
          rwl.ReleaseReaderLock();
        }
        return result;
      }
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now