On Sun, Jun 18, 2006 at 11:07:41PM -0400, Tom Lane wrote:
> "Bort, Paul" <pbort@tmwsystems.com> writes:
> >> Anyone know a variant of this that really works?
>
> > Here's a theory: If the counter is bumped to an odd number before
> > modification, and an even number after it's done, then the reader will
> > know it needs to re-read if the counter is an odd number.
>
> Great minds think alike ;-) ... I just committed exactly that protocol.
> I believe it is correct, because AFAICS there are only four possible
> risk cases:
>
> * reader's read starts before and ends after writer's update: reader
> will certainly note a change in update counter.
>
> * reader's read starts before and ends within writer's update: reader
> will note a change in update counter.
>
> * reader's read starts within and ends after writer's update: reader
> will note a change in update counter.
>
> * reader's read starts within and ends within writer's update: reader
> will see update counter as odd.
>
> Am I missing anything?
>
> Note in particular that this protocol does not assume atomic update
> of the counter, so we don't need to worry about whether int is
> sig_atomic_t. If any of the bytes change, we have what we need.
> We could use a counter narrower than int, but then there's some tiny
> risk that the counter could wrap all the way around while the reader
> is blocked.
>
> regards, tom lane
>
The reader needs to read the counter/version at the beginning of
the read and then again after the read. If the value is the same,
it can assume that the read/data is okay. I am assuming that there
is only one possible writer, otherwise the writer will need to
lock the area from other writers. This can be done with an atomic
instruction such as compare-and-swap or test-and-set.
Ken Marshall