2

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

  • Is this a homework/exercise? RW locks are a bit tricky, but most environments have built-in implementations you should use. But suggesting you call a library doesn't help if you're doing an exercise. – Pete Kirkham May 20 '10 at 07:36
  • This is not a homework. Most of the books either discusses one or two of these system type. I wanted to have a collection, where for each kind of system, we can understand how the things in theory works. –  May 20 '10 at 08:50

2 Answers2

0

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
  • 6,595
  • 3
  • 41
  • 54
0

If you want to use Java you can try ReentrantReadWriteLock.

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

Eric Eijkelenboom
  • 6,943
  • 2
  • 25
  • 29