Re: Read/write locks

Linus Torvalds (torvalds@transmeta.com)
Sun, 21 Sep 1997 17:27:38 -0700 (PDT)


On Sun, 21 Sep 1997, Colin Plumb wrote:
>
> > I _think_ the only thing you'd need to do to distinguish a write lock
> > from an update lock is that the update-lock doesn't need to wait for
> > readers to go away (you do that only if/when you decide to really
> > upgrade to a real write lock).
>
> And since the current locks are implemented this way anyway, it just
> consists of splitting the code into two parts.

Yes, that was my thinking also. It doesn't work quite that way right now,
as you already noticed:

> In fact, the current code does *not* do this. It lets new readers in
> while a writer is trying to get a write lock, which leaves open the
> possibility of starvation for the writer - a continuous stream of readers
> can leave the writer blocked forever.

Yes. This is not really for any good reason, I just happen to prefer
readers over writers, although I suspect I shouldn't (it only complicates
the code for no real good reason).

Other than that we're rather close to already doing update locks, in some
sense (the current write-lock is otherwise essentially an update lock plus
waiting for the readers to finish, with the exception noted above).

> It seems odd that the code clears the writer-locked bit (bit 31) if there
> are readers present. Wouldn't it make more sense to block incoming readers
> while a writer is contending?

As mentioned, I tend to prefer readers over writers, on the (probably
totally silly) assumption that as we can have more parallellism with
readers we should try to allow it as far as possible.

However, as the basic premise should be that there is almost never
contention anyway, the above silly idiosyncracy of mine is probably
totally without any technical merit. Oh, well..

> If you want the reader-priority scheme, then a write lock actually
> gets simpler given CAS, CMPXCHG, or the like.

Yes. I've tried to avoid using them as they do not work on 386's, and
while I don't support SMP on 386 machines I _do_ hesitate to throw away
the notion of a "generic kernel". In particular, a SMP-enabled kernel that
works on UP 386's would be able to work on any PC - which can be useful in
any environment that has different PC's but want to share a single kernel
for maintenance reasons, for example.

However, the SMP kernel doesn't seem to work 100% reliably on all UP PC's
anyway (and i386's are becoming increasingly rare, especially in any
environment where a SMP-Linux would be an issue in the first place), so if
there was enough of an incentive to use the newer instructions I would
probably drop this dream in a jiffy. So far there hasn't been enough
reason to do so, though, as the i386 instructions have been enough (not
perfect, but not so bad as to be a problem).

Linus