> 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