Boost logo

Boost Users :

From: Gottlob Frege (gottlobfrege_at_[hidden])
Date: 2007-02-09 20:40:24


On 2/8/07, Anders Sundman <anders.sundman_at_[hidden]> wrote:
>
> Hi all!
>
> I'm curious about the realization of the boost::mutex class (especially
> on W32).
>
> * How heavy is it to create a mutex object?

similar to InitializeCriticalSection() of W32. Not huge, but it noticeable
- usually it is better to create it once and keep it around.

* Are there any limits (OS recource bound or other) to how many mutex
> object that can be created?

I think W32 has limits, but I'm not sure what they are

* How costly is it to 're-lock' a recursive mutex? Almost NOP or more
> costly?

A few 'if' statements and a InterlockedCompareExchange().
For some real numbers, see Herb Sutter's http://www.gotw.ca//gotw/045.htm.

Are these questions (and other of the same type) answered somewhere in
> the docs?
>
>
> Finally, a more concrete question. Consider the following:
>
> A list of objects that needs to lock a mutex (all lock the same mutex).
>
> vector<CriticalWorker*> foo;
> ...
> for ( ... i = each foo ... )
> i->doWorkThatLocks();
>
> This code section will lock/unlock repeatedly.
>
> If I use a recursive mutex, will the following be much faster (since the
> locks in 'doWorkThatLocks' will be more light-weight)?
>
> lock();
> for ( ... i = each foo ... )
> i->doWorkThatLocks();
> unlock();

In general, I would say the outer lock (ie second case) is better. But it
depends:

- how much work does 'doWork' do? If each call takes seconds (which is
forever in computer time), then the lock/unlock won't be noticeable.
- what are the chances that some other thread wants/needs to use the
vector? Is it important that they don't wait 'forever'? Maybe you need to
look at 'readers' vs 'writers' (ie allow multiple threads to read the vector
as long as no one is writing to it), or even consider a custom container
that allows 'lock-free' access or locks per item, etc. Depends on the
situation.

- premature optimization is the root of all evil.

Best Regards
> Anders Sundman

Tony



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net