This forum has been archived. All content is frozen. Please use KDE Discuss instead.

thread-safety bug

Tags: None
(comma "," separated)
max.b
Registered Member
Posts
7
Karma
0

thread-safety bug

Sat Jan 04, 2014 10:26 am
The documentation says Eigen can be safely used in multithreaded code, as long as initParallel is called before the threads are created.

However, Random calls std::rand, which is not thread-safe (on Linux anyway)
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: thread-safety bug

Sat Jan 04, 2014 6:59 pm
Good point. This has to be fixed in the documentation. As for std::rand, the workaround is to use the new c++11 random feature or boost::random, or whatever other good random number generator implementation. Here is an example showing how to use c++11 random distributions with Eigen:

Code: Select all
#include <Eigen/Sparse>
#include <iostream>
#include <random>

using namespace Eigen;

int main() {
  std::default_random_engine generator;
  std::poisson_distribution<int> distribution(4.1);
  auto poisson = [&] (int) {return distribution(generator);};

  RowVectorXi v = RowVectorXi::NullaryExpr(10, poisson );
  std::cout << v << "\n";
}


I'll also add that example in the doc.
max.b
Registered Member
Posts
7
Karma
0

Re: thread-safety bug

Sat Jan 04, 2014 8:40 pm
Docs:

Your example doesn't show how to use PRNG in parallel correctly.

Challenge: seed the PRNG, then start a loop that estimates the variance of random elements -- the results should be deterministic. Now, parallelise the loop, but make sure the results stay deterministic (for a given seed).

Code

I would suggest placing a common lock on all Random procedures. This doesn't fix the issue completely, but it's better than nothing.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: thread-safety bug

Sun Jan 05, 2014 1:12 pm
Yes I known that example does not show multi-threading. Then how to initialise the generator(s) depend on the application. For some use cases it is fine to let each thread has its own generator initialized with its own seed, and sometimes one even want that each thread generates the same sequence.

I don't feel comfortable in adding a lock to the *Random functions because 1) this would introduce a dependency to a third party library offering a portable mutex implementation (or use omp and enforce users doing multi-threading to also use an omp compliant compiler and enable omp) ; and 2) Eigen is quite low level library, just like there is no lock in std::rand (because of performance penalties), it makes sense for Eigen do delegate this responsibility to the user.


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], Yahoo [Bot]