c++ - 线程,如何独立播种随机数生成器?

标签 c++ multithreading random

我昨天在这里问了一个关于线程和获取输入以创建用户指定的线程数量的问题。在你的帮助下,我能够弄清楚。除了这一次,我正在处理同一个程序,我需要帮助让我的程序中的每个线程独立地为随机数生成器提供种子。如果这听起来很简单,我深表歉意。我对线程还是陌生的。

基本上我的程序正在做的是询问用户他们想要创建多少线程,以及他们想要 throw 多少箭头。每个箭头将生成 2 个数字,从 -1 到 1。这是我目前的程序。它是工作代码,因此您可以在需要时运行它:

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <thread>

using namespace std;

void exec(int n, int randNumbers)
{
    int seed = 0;

    srand(seed);
    int random_number = rand() % 1 + -1;

    cout << "Thread " << n << endl;
    cout << "\n";

    while (randNumbers != 0)
    {
        srand(seed);
        cout << random_number << endl;
        seed++;
        cout << "Seed: " << seed << endl;
        cout << "\n";

        cout << random_number << endl;
        seed++;
        cout << "Seed: " << seed << endl;
        cout << "\n";
        randNumbers--;
    }
}


int main()
{
    int numThreads = 0; // Threads
    int maxRandom; // Arrows

    cout << "This is a Monte Carlo simulation." << endl;
    cout << "Please enter the number of threads to run." << endl;
    cout << "Threads: ";

    cin >> numThreads;

    // create an array of threads
    thread* myThreads = new thread[numThreads];

    if ((numThreads > 20) || (numThreads < 1))
    {
        cout << "Sorry. Something went wrong." << endl;
        return 0;
    }

    system("CLS");
    cout << "\n";
    cout << "Enter the number of arrows you would like to throw: " << endl;
    cout << "Arrows: ";

    cin >> maxRandom; // Arrows

    system("CLS");
    for (int i = 0; i < numThreads; i++)
    {
        // run random number generator for thread at [i]
        myThreads[i] = thread(exec, i, maxRandom);
    }

    for (int i = 0; i < numThreads; i++)
    {
        myThreads[i].join();
    }

    cout << "Done!" << endl;
}

无论 int seed 是否增加 1,所有线程都返回 -1。我已经查看了所有内容,但似乎仍然无法弄清楚为什么我的线程没有独立播种随机数发生器。有人知道发生了什么事吗?我对线程还是陌生的。任何帮助将不胜感激。非常感谢。

最佳答案

  1. 确保每个线程都有其自己的私有(private) PRNG(所有线程使用一个共享的 PRNG 需要锁定,并且由于等待和缓存争用会非常慢)。
  2. Katzgraber 在 Random Numbers in Scientific Computing: An Introduction 的第 7.1 节中提出了一种基于进程/线程数的 PRNG 播种。 .

看起来像:

long seedgen(void) {
    long s, seed, pid; // pid from 0 to number of processes/threads - 1
    pid = ...; /* get processt/thread ID */
    s = time ( &seconds ); /* get CPU seconds since 01/01/1970 */
    seed = abs(((s * 181) * ((pid - 83) * 359)) % 104729);
    return seed;
}

关于c++ - 线程,如何独立播种随机数生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36802457/

相关文章:

java - Solaris 上 Java 线程与 CPU 的最佳比例是多少?

javascript - 从数组中获取随机数,不重复(使用计时器)

c++ - 我应该在我的库中使用线程吗?

c++ - 使用带有 ldap_sasl_bind_s 函数的 kerberos 凭证通过 GSSAPI 进行 SASL 绑定(bind)

ruby-on-rails - 在运行时更改数据库连接

Java-并发 : LinkedBlockingQueue, "try again if failed"

c - 预测由 C (glibc) rand() 生成的下一个数字

swift - 生成一定数量的数字的随机数

c++ - C++中是否可以在另一个类的构造函数中声明一个类的对象?

c++ - 可变参数函数 va_arg() 返回不正确的参数