views:

29

answers:

2

Hi,

Lets say, I have a reader-writer system where reader and writer are concurrently running. 'a' and 'b' are two shared variables, which are related to each other, so modification to them needs to be an atomic operation.

A reader-writer system can be of the following types:

  1. rr
  2. ww
  3. r-w
  4. r-ww
  5. rr-w
  6. rr-ww

where
[ r : single reader
rr: multiple reader
w : single writer
ww: multiple writer ]

Now, We can have a read method for a reader and a write method for a writer as follows. I have written them system type wise.

  1. rr

    read_method
    { read a; read b; }
    
  2. ww

    write_method
    { lock(m); write a; write b; unlock(m); }
    
  3. r-w

  4. r-ww
  5. rr-w
  6. rr-ww

    read_method
    { lock(m); read a; read b; unlock(m); }
    
    
    write_method
    { lock(m); write a; write b; unlock(m); }
    

For multiple reader system, shared variable access doesn't need to be atomic.

For multiple writer system, shared variable access need to be atomic, so locked with 'm'.

But, for system types 3 to 6, is my read_method and write_method correct? How can I improve?

Sincerely,
Srinivas Nayak

+1  A: 

If you want to use .NET you can try ReaderWriterLockSlim. I believe it gives you the exact functionality you need. You can also read about the way they implemented it to learn how to implement such locks yourself.

brickner
+1  A: 

If you want to use Java you can try ReentrantReadWriteLock.

You can find several tutorials on its usage, e.g. here.

Eric Eijkelenboom