How do I program a critical section for read-write systems?
Let's say I have a read-write system in which a reader and a writer work at the same time. "a" and "b" are two shared variables that are related to each other, so modifying them should be an atomic operation.
The read-write system can be of the following types:
- rr
- Ww
- g-w
- g-ww
- p-p-f
- r-r-zhv
where
[r: single reader
rr: multiple reader
w: single writer
ww: multiple writer]
We can now have a reader for the reader and a writer for the writer as follows. I wrote them system type wise.
-
rr
read_method { read a; read b; }
-
ww
write_method { lock(m); write a; write b; unlock(m); }
-
g-w
- g-ww
- p-p-f
-
r-r-ww
read_method { lock(m); read a; read b; unlock(m); } write_method { lock(m); write a; write b; unlock(m); }
For a system with multiple readers, access to a shared variable does not have to be atomic.
For a multiple notation system, shared access to a variable must be atomic, so locked with "m".
But for system types 3-6, is my read_method and write_method correct? How can I improve?
Best regards,
Srinivas Nayak
If you want to use Java you can try ReentrantReadWriteLock .
You can find several tutorials on how to use it, for example. here .
a source to share
If you want to use .NET you can try ReaderWriterLockSlim . I believe it gives you the exact features you need. You can also read about how they implemented it to learn how to implement such locks yourself.
a source to share