bab2min / EigenRand

Fastest Random Distribution Generator for Eigen
https://bab2min.github.io/eigenrand/
MIT License
92 stars 13 forks source link

Is it thread safe? #25

Closed soraxas closed 3 years ago

soraxas commented 3 years ago

Hi! Thanks for the great library. I haven't seen this being mentioned in the docs or issues, so I just wanna ask to see if this library is thread safe, and more importantly, would the random number generator seeded uniquely across different threads?

Say if I have spawned multiple threads, and each of them constructed their own instances of Eigen::Rand::Vmt19937_64{}(i.e. Without fixed random seed). Would different thread guarantees to produce different random numbers?

I know some libraries (e.g. Eigen's own Rand) doesn't work across threads as they are not re-entrant

note that all functions generating random matrices are not re-entrant nor thread-safe. Those include DenseBase::Random(), and DenseBase::setRandom() despite a call to Eigen::initParallel(). This is because these functions are based on std::rand which is not re-entrant.

https://eigen.tuxfamily.org/dox/TopicMultiThreading.html

A different scenario would be a master thread constructs a Eigen::Rand::Vmt19937_64{}and each slave threads holds a reference to the same instance. I would assume it will not be thread safe in this case?

bab2min commented 3 years ago

Hi @soraxas No, a random number generator of EigenRand is not thread-safe. You should not share the same instance across threads, but construct an instance of Vmt19937_64 for each thread. Since the default constructor of Vmt19937_64 use a fixed default seed, you initialize them ​with different seeds if you want to produce different random number across thread. I recommend use std::random_device{}() as the seed for each thread's Vmt19937_64.

soraxas commented 3 years ago

Hi @bab2min thanks for your kind reply and suggestions! Yeah I figured that it will likely be not thread-safe, and I'm just mostly interested in whether constructing multiple Vmt19937_64 in different threads at approximately the same time would result in distinct random seed or not (I had tested it a bit and it seems to be ok but just wondering if it is guaranteed to work in general). I will use your recommendation of std::random_device as seed in different thread, thanks:)