write/read thread safe

http://www.artima.com/designtechniques/threadsafetyP.html (just FMI)

requirement:

1) when read, does not allow any write, but allow other read

2) when write, no read, no other write

int ReadCounter = 0; 
   get
        {
            slimLock.EnterReadLock();  // used to lock the operation on changing Readcounter (see comments)
            if (ReadCounter++ == 0) //when there is read, don't allow write
               { slimLock.EnterWriteLock(); }
            var returnValue = notSafeField;
            slimLock.ExitReadLock();  // need to keep it; because it locks only the part of increasing ReadCounter, 
                                     // the part of read or return value is not locked so other read can concurrency
                                     // should I move this one line above?

            if (--ReadCounter == 0)
                { slimLock.ExitWriteLock(); }

            return returnValue;
        }
 set
        {
            slimLock.EnterWriteLock();
            notSafeField = value;
            slimLock.ExitWriteLock();
        }

I delete the readLock in the get method to allow other read threads, is that correct?
I don't understand why it is there. 

2 thoughts on “write/read thread safe

  1. Read lock protects this operation which is actually two operations
    ReadCounter++ == 0

    ReadCounter initialized to 0
    Thread 1 checks that ReadCounter == 0 — ‘if’ is true
    Thread 2 checks that ReadCounter == 0 — ‘if’ is true
    Thread 2 increments ReadCounter to 0+1 = 1
    Thread 1 increments ReadCounter to 0+1 = 1 — error…should be 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s