Boost logo

Boost Users :

From: anthony_w.geo_at_[hidden]
Date: 2008-05-20 04:31:10


Jason Robertson <jvrobert_at_[hidden]> writes:

> I'm trying to create simple locks based on a string name.  I looked
> at the interprocess module which has a named mutex, but it seems not
> well suited/efficient for use in a single process, though I know
> it's supposed to work. Instead, I'm just creating a
> map<string,weak_ptr<mutex>> in a NamedMutexManager class.  It's used
> as a singleton and uses brute force locking to implement a named
> lock pattern.  Main method is

> shared_ptr<mutex> GetMutex(string name) {
> BigLock (only one thread at a time can get a lock so we synchronize access to map)
> check map
>     if we have entry, make sure weak_ptr hasn't been reclaimed
>         If so, make a new shared_ptr, save weak_ptr by name, return shared_ptr
>         If not, return shared_ptr copy from weak_ptr.lock()
>     If we habe no entry,
>         make a new shared_ptr, save weak_ptr by name, return shared_ptr
> }

> I'm just getting back to C++ after years, so I'm 99% sure there's
> probably a much better way.  Is there a better way to do an
> intra-process, reliable mutex by std::string name so I can lock
> things by name?  How are other people doing this, do you find
> interprocess:named_mutex suitable for use in-process?  I had
> problems with it. Thanks! Jason

A common way to do named mutexes is with a hash table. In the absence
of a true concurrent hash table, you can use a fixed number of
buckets, with a mutex on each. You then hash the name to choose a
bucket, lock the appropriate mutex and search the bucket for the
entry, adding a new one if not there.

Anthony

-- 
Anthony Williams            | Just Software Solutions Ltd
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

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