Reputation: 3438
I tried using rand()
function to create random numbers in each thread in a multi-threaded C++ program. I ended up getting much worse results as I was increasing the number of threads. Thanks to this post, I found that because it needs to keep track of the states, rand()
uses a lock for every call.
Does using C++11 random library (this usage as an example) do the same procedure and I should expect the same observation if I use it? Or C++11 can provide a way around?
Upvotes: 1
Views: 1416
Reputation: 490098
Yes and no. Most of the C++11 random number generators are objects that encapsulate their own state, so as long as you create a separate generator object for each thread, each should be able to operate independently of the others (so you don't need any locking).
The specific case of std::random_device
is a little different though: this is intended (but not guaranteed) to obtain truly non-deterministic data from some sort of random number generation hardware. The driver for that device may well impose locking requirements of its own -- and it's often fairly low bandwidth as well, so if you want to obtain a lot of numbers quickly, it's usually a poor choice.
In a typical case, you want to use one generator (other than std::random_device
) per thread, and use std::random_device
only to provide the initial seeds for those other generators. This may impose locks during that initialization, but then allows each thread to generate its random numbers without any interlock with other threads.
Upvotes: 7