Dynamic reads without locking.

Bernd Walter ticso at cicely12.cicely.de
Wed Oct 8 05:02:04 PDT 2003


On Wed, Oct 08, 2003 at 12:12:22PM +0200, Pawel Jakub Dawidek wrote:
> On Wed, Oct 08, 2003 at 11:51:06AM +0200, Harti Brandt wrote:
> +> You need to lock when reading if you insist on consistent data. Even a
> +> simple read may be non-atomic (this should be the case for 64bit
> +> operations on all our platforms). So you need to do
> +> 
> +> mtx_lock(&foo_mtx);
> +> bar = foo;
> +> mtx_unlock(&foo_mtx);
> +> 
> +> if foo is a datatype that is not guaranteed to be red atomically. For
> +> 8-bit data you should be safe without the lock on any architecture. I'm
> +> not sure for 16 and 32 bit, but for 64-bit you need the look for all
> +> our architectures, I think.
> 
> But I'm not talking about non-atomic reads. What I'm want to show is that
> even atomic read (without lock) is dangerous in some cases.
> 
> +> If you don't care about occasionally reading false data (for statistics or
> +> such stuff) you can go without the lock.
> 
> I'm afraid that many developers thinks that atomic reads are always safe
> without locks (there are many such reads in sources). I hope I'm wrong.

It depends on the architecture and usage.
bar = foo might be non-interruptable, but that doesn't say anything
about cache consistency.
If foo was written by another thread then you can have trouble with
register caching unless the variable is volatile.
If the other thread was/is running on another CPU then you might read
an outdated value from cache.
mtx_lock/mtx_unlock takes care about caching.

However - if you read a value (e.g.) for statistic output - then it
won't hurt to get a cached value which is a few subseconds behind the
real value.
The only point to take care in this case is that the read is atomic and
that all bytes in the read value are consistent.

The above mtx_lock/read/mt_unlock case doesn't make sense, because it
only garanties an up to date value, but you cache it in a local
variable which again brings it out of date when used outside the lock.

-- 
B.Walter                   BWCT                http://www.bwct.de
ticso at bwct.de                                  info at bwct.de



More information about the freebsd-hackers mailing list