Boost logo

Boost :

From: bill_kempf (williamkempf_at_[hidden])
Date: 2002-02-11 13:43:19


--- In boost_at_y..., "Peter Dimov" <pdimov_at_m...> wrote:
> From: "Wyss, Felix" <felixw_at_i...>
> > > I'd love to simply use a pthread_mutex/CRITICAL_SECTION (a
critical
> section
> > > is a 'foolproof spinlock', it spins for a while, then falls
back to a
> mutex)
> > > but people were (are) concerned about their efficiency.
> >
> > That is correct, but the Win32 CRITICAL_SECTION structure uses 24
bytes
> compared to 4 bytes for a simple atomic-exchange based spin-lock.
As for
> efficiency: unless there is a lot of contention, I would expect two
atomic
> exchanges to incur the same overhead as two atomic
increment/decrement
> operations (as in the current implementation of counted_base).
> <
>
> If that's true, why do people bother with critical sections and
pthread
> mutexes instead of simply using spinlocks? :-)

It is true. There are a couple of reasons to not use a spin lock,
though.

1) Spin locks, by themselves, are prone to memory visibility issues.

2) Spin locks use "busy waits" and thus chew up CPU resources while
trying to acquire the lock. Unless the lock contention is low this
overhead can quickly become detrimental to the performance of the
application.

The first can be ignored for some platforms (but then the code isn't
portable and best be hidden in the implementation). And in this case
the second is problem not an issue either, since the lock will only
be held long enough to increment/decrement the count, thus requiring
little lock contention even if there are a lot of threads trying to
acquire the lock simultaneously.

However, if it were me, I'd stick with the mutex/critical section
since it's easy to maintain and is more portable.

Bill Kempf


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk