并发随机数生成 [英] Concurrent random number generation

查看:148
本文介绍了并发随机数生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用open mp编写一个并行程序,其中我生成一个随机浮点数矩阵,然后对其进行一些计算。我目前想做的步骤,我生成矩阵并行运行,但我有问题,rand()函数并不意味着并发运行。我不想使用锁提供互斥对兰德,因为这是唯一的事情在循环中完成,它可能只是更有效地顺序运行它。

I'm writing a parallel program using open mp in which I generate a matrix of random floating point numbers and then do a number of calculations on it. I currently want to make the step where I generate the matrix run in parallel, but I have the problem that the rand() function was not meant to run concurrently. I don't want to use locks to provide mutex on rand because this is the only thing being done in the loop and it would probably just be more efficient to run it sequentially. Is there any way to do this step efficiently in parallel?

这里如果这部分的当前代码(在rand上输出mutex);

Here if the current code for this part (with out mutex on rand);

#pragma omp parallel default(private)
{
    int i= omp_get_thread_num();
    for(int j=0; j<cols; j++)
        matrix[i][j]= rand()%1000 + (float)(rand()%100)/(float)(rand()%1000);
}


推荐答案

,则应考虑使用 Boost库随机号码类 。您可以为每个线程创建一个唯一的PRNG实例。如果您需要重复性,您可以在主线程中初始化每个实例,并重复生成种子值。

If you're using C++, you should consider using the Boost library random number classes. You can create a unique PRNG instance for each thread. If you require repeatability, you can initialize each instance in your main thread with repeatably generated seed values.

这篇关于并发随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆