ptg10805159
752 ADatabase Library Chapter 20
The user processes that call the functions in the database library to perform I/O are
considered cooperating processes, since they use byte-range locking to provide
concurrent access.
20.6 Concurrency
We purposely chose a two-file implementation (an index file and a data file) because
that is a common implementation technique (it simplifies space management in the
files). Itrequires us to handle the locking interactions of both files. But thereare
numerous ways to handle the locking of these two files.
Coarse-Grained Locking
The simplest form of locking is to use one of the two files as a lock for the entire
database and to requirethe caller to obtain this lock beforeoperating on the database.
We call thiscoarse-grained locking.For example, we can say that the process with a read
lock on byte 0 of the index file has read access to the entiredatabase. A process with a
write lock on byte 0 of the index file has write access to the entiredatabase. Wecan use
the normal UNIX System byte-range locking semantics to allow any number of readers
at one time, but only one writer at a time. (Recall Figure14.3.) The functions
db_fetchanddb_nextrecrequirearead lock, anddb_delete,db_store,and
db_openall requireawrite lock. (The reasondb_openrequires a write lock is that if
the file is being created, it has to write the empty free list and hash chains at the front of
the index file.)
The problem with coarse-grained locking is that it limits concurrency.Ifaprocess is
adding a record to one hash chain, another process should be able to read a record on a
different hash chain.
Fine-Grained Locking
We enhance coarse-grained locking to allow moreconcurrency and call thisfine-grained
locking.Wefirst requireareader or a writer to obtain a read lock or a write lock on the
hash chain for a given record. Weallow any number of readers at one time on any hash
chain but only a single writer on a hash chain. Next, a writer needing to access the free
list (eitherdb_deleteordb_store)must obtain a write lock on the free list. Finally,
whenever it appends a new record to the end of either the index file or the data file,
db_storehas to obtain a write lock on that portion of the file.
We expect fine-grained locking to provide moreconcurrency than coarse-grained
locking. In Section 20.9, we show some actual measurements. In Section 20.8, we show
the source code for our implementation of fine-grained locking and discuss the details
of implementing locking. (Coarse-grained locking is merely a simplification of the
locking that we show.)
In the source code, we callread,readv,write,andwritevdirectly.We do not
use the standardI/O library.Although it is possible to use byte-range locking with the
standardI/O library,careful handling of buffering is required. Wedon’t want an