Boost logo

Boost :

Subject: Re: [boost] [uuids] generating uuids from multiple threads
From: Edouard A. (edouard_at_[hidden])
Date: 2009-01-09 04:55:57


On Fri, 09 Jan 2009 03:48:05 -0600, Michael Marcin <mike.marcin_at_[hidden]>
wrote:

> For one thing this is yet another case where I used a default
> constructor on a uuid during natural coding and expected it to be cheap
> but I digress.
>
> Do I have to protect the shared generator with a mutex? Should I even be
> using a shared generator or should I be constructing it on the stack in
> this function? I don't expect this to be called very often (twice total
> in our current application) but I want to make sure it is bullet proof
> since it can potentially be called concurrently.

A PRNG is stateful, hence concurrent access lead need to be protected, but
your mutex needs to be static, of course.

I just had exactly the same need and I did protect it with a mutex. You
will probably also have the need to do a "init once" for your PRNG.

I did something like this for the init :

        static boost::hellekalek1995 rng;
        static boost::mutex mutex;
        static volatile bool initialized = false;

        if (!initialized)
        {
                // double checking pattern
                boost::lock_guard<boost::mutex> lock(mutex);
                if (!initialized)
                {
                  // do the init
                  rng.seed(blah blah blah);
                  initialized = true;
                }
        }

-- 
EA

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