Re: Upgradeable read locks for USB

Colin Plumb (colin@nyx.net)
Sat, 10 Jan 1998 21:08:19 -0700 (MST)


Sir Linus uttereth unto the great unwashed:
> Actually it wouldn't be all that hard to have two versions of the update
> lock: one that prefers reading and one that prefers writing. My update
> lock prefers writing, but I could do one that prefers reading: it wouldn't
> be all that much different (I'd use bit 30 instead of 31 as the "update"
> lock - that will automatically also lock out writers but wouldn't lock out
> readers). HOWEVER, I can't easily make a lock that can share both
> semantics at the same time depending on what you consider to be the more
> likely case.

> So do people think that the reader-prefering version would be better? I
> don't want to have both because of the possibility of mixups (the code
> might appear correct, but if somebody ever mixed them the results would be
> unpredictable - you could get dead-locks if two different kinds of upgrade
> locks were entered at the same time - they wouldn't be mutually exclusive
> but upgrading to a write lock certainly _would_ be).

You can do it either way, really, but actually I like the writer-priority
version. By starting the clearing out of the writers early, it reduces
the expected wait time when it does upgrade. Also, it's slightly
more efficient, as there's no need to set a second flag when you do the
upgrade.

It's pretty trivial to build the reader-priority version if you really
need it.

You can also do a slightly inefficient but useful optimistic locking
hack, based on a try_to_upgrade operation that turns read -> upgrade
(by trying to set bit 0x80000000, then decrementing if successful),

wherein you

read
if condition not satisfied, drop lock and return
if (!try_to_upgrade_read_to_upgrade) {
drop read lock
get update lock
if (condition not satisfied)
drop lock and return
}
collect any other data needed
upgrade to write lock
make the modification
drop the write lock

Anyway, I think it's easy to build the reader-priority lock if you really
need it, but the writer-priority one is more difficult, so if you rovide
the latter, both are available if needed.

-- 
	-Colin