线程,如何独立种子随机数生成器?

时间:2016-04-22 20:05:54

标签: c++ multithreading random

我昨天在这里问了一个关于线程和获取输入以创建用户指定的线程数量的问题。我能够在你的帮助下弄明白这一点。我正在使用相同的程序,除了这次,我需要帮助让我的程序中的每个线程独立播种随机数生成器。如果这听起来很简单,我会道歉。我还不熟悉线程。

基本上我的程序正在做的是询问用户他们想要创建多少个线程,以及他们想要抛出多少箭头。每个箭头将生成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 个答案:

答案 0 :(得分:1)

  1. 确保每个线程都有自己的私有PRNG (所有线程使用一个共享PRNG需要锁定,并且由于等待和缓存争用而非常慢)。
  2. Katzgraber根据Random Numbers in Scientific Computing: An Introduction第7.1节中的流程/线程编号提出了PRNG的播种。
  3. 看起来像:

    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;
    }