Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 8 Oct 2003 14:01:35 +0200
From:      Bernd Walter <ticso@cicely12.cicely.de>
To:        Pawel Jakub Dawidek <nick@garage.freebsd.pl>
Cc:        hsu@freebsd.org
Subject:   Re: Dynamic reads without locking.
Message-ID:  <20031008120134.GA13791@cicely12.cicely.de>
In-Reply-To: <20031008101222.GB520@garage.freebsd.pl>
References:  <20031008083059.GA520@garage.freebsd.pl> <20031008114506.I63940@beagle.fokus.fraunhofer.de> <20031008101222.GB520@garage.freebsd.pl>

next in thread | previous in thread | raw e-mail | index | archive | help
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@bwct.de                                  info@bwct.de



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20031008120134.GA13791>