Boost logo

Boost Users :

Subject: Re: [Boost-users] thread-safe boost::random_device / boost:mt19937
From: Brian Budge (brian.budge_at_[hidden])
Date: 2012-12-27 18:18:32


On Thu, Dec 27, 2012 at 6:25 AM, Philipp Kraus
<philipp.kraus_at_[hidden]> wrote:
> On 2012-12-24 18:20:06 +0100, Brian Budge said:
>
>> On Thu, Dec 20, 2012 at 8:26 AM, Philipp Kraus
>>
>> If possible, can you construct an object per thread?
>
>
> I don't know, because I call the Boost random calls from a Lua script
> and initialize the boost random object with a static member globally
> over all threads (and MPI cores).
>
>
>> This is
>> typically the way that I have used these wrappers (and actually the
>> reason for writing them). If you need a specific sequence, it might
>> make sense to generate many random numbers up-front, and then use them
>> in the thread. If all else fails, you can use your own boost::mutex
>> and boost::lock_guard to ensure thread safety.
>
>
> At the moment I think a own object on each thread is a good choice, but
> I must change same design structures, so a mutex is a faster way to solve
> it

The mutex will solve the problem in about 2 minutes; however, you
should be aware that if the threads are generating very many random
values, this may quickly degrade performance (you might get worse
performance than with a single thread).

One possible workaround would be to use a thread local variable for
the RNG. boost.thread also provides these via (I believe)
thread_specific_ptr. Although it will still decrease performance a
little, it should scale much better with the number of threads. You
just have to ensure that each RNG is seeded differently.

  Brian


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