Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 20.8 Source Code 763


230 /*
231 * Find the specified record. Called by db_delete, db_fetch,
232 * and db_store. Returns with the hash chain locked.
233 */
234 static int
235 _db_find_and_lock(DB *db, const char *key, int writelock)
236 {
237 off_t offset, nextoffset;
238 /*
239 * Calculate the hash value for this key, then calculate the
240 * byte offset of corresponding chain ptr in hash table.
241 * This is where our search starts. First we calculate the
242 * offset in the hash table for this key.
243 */
244 db->chainoff=(_db_hash(db, key) * PTR_SZ) + db->hashoff;
245 db->ptroff=db->chainoff;
246 /*
247 * We lock the hash chain here. The caller must unlock it
248 * when done. Note we lock and unlock only the first byte.
249 */
250 if (writelock) {
251 if (writew_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
252 err_dump("_db_find_and_lock: writew_lock error");
253 } else {
254 if (readw_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
255 err_dump("_db_find_and_lock: readw_lock error");
256 }
257 /*
258 * Get the offset in the index file of first record
259 * on the hash chain (can be 0).
260 */
261 offset=_db_readptr(db, db->ptroff);

[230 – 237] The_db_find_and_lockfunction is used internally by the library to find
arecordgiven its key.Weset thewritelockparameter to a nonzerovalue
if we want to acquireawrite lock on the index file while we search for the
record. If we setwritelockto zero, we read lock the index file while we
search it.
[238 – 256] We prepare to traverse a hash chain in_db_find_and_lock.Weconvert
the key into a hash value, which we use to calculate the starting address of
the hash chain in the file (chainoff). Wewait for the lock to be granted
beforegoing through the hash chain. Note that we lock only the first byte in
the start of the hash chain. This increases concurrency by allowing multiple
processes to search different hash chains at the same time.
[257 – 261] We call_db_readptrto read the first pointer in the hash chain. If this
returns zero, the hash chain is empty.
Free download pdf