Data races are a concern only when shared data is modified. Multiple
threads reading the shared data do not present a problem. Read-only data does
not, therefore, need protec-tion with some kind of lock.
However, sometimes data that is typically read-only
needs to be updated. A readers-writer
lock (or multiple-reader lock)
allows many threads to read the shared data but can then lock the readers threads out to allow one thread to acquire a
writer lock to modify the data.
A writer cannot acquire the write lock until all
the readers have released their reader locks. For this reason, the locks tend
to be biased toward writers; as soon as one is queued, the lock stops allowing
further readers to enter. This action causes the number of readers holding the
lock to diminish and will eventually allow the writer to get exclu-sive access
to the lock.
The code snippet in Listing 4.9 shows how a
readers-writer lock might be used. Most threads will be calling the routine readData() to return the value from a particular pair of cells. Once a thread has
a reader lock, they can read the value of the pair of cells, before releasing
the reader lock.
To modify the data, a thread needs to acquire a
writer lock. This will stop any reader threads from acquiring a reader lock.
Eventually all the reader threads will have released their lock, and only at
that point does the writer thread actually acquire the lock and is allowed to
update the data.
Listing 4.9 Using
a Readers-Writer Lock
readData( int cell1, int cell2 )
int result = data[cell] + data[cell2];
writeData( int cell1, int cell2, int value )
data[cell1] += value;
data[cell2] -= value;