线程中的随机数生成器不断返回相同的值

时间:2019-05-01 19:32:06

标签: c++ multithreading random

我正在尝试进行蒙特卡洛模拟以计算pi。 我需要每个线程生成2个随机数(介于1和0之间的x和y值)以对模拟进行采样,到目前为止,我正在尝试使一个线程工作,但是它始终生成相同的数字。

#include "pch.h"

#include <iomanip>
#include <iostream>
#include <cmath>
#include <thread>
#include <mutex>
#include <cstdlib>
using namespace std;


long double sampleCount = 0;
long double circleSamples = 0;
long double proportion;
mutex m;

void simulate()
{
    long double sampleX;
    long double sampleY;
    long double sampleHypotenuse;

    //Generate Random values for x and y
    sampleX = (long double)std::rand() / RAND_MAX;
    sampleY = (long double)std::rand() / RAND_MAX;

    // Find the distance from the center of the sample area
    sampleHypotenuse = sqrt(pow(sampleX - .5, 2) + pow(sampleY - .5, 2));


    m.lock();

    //Find if sample is within a radius of .5 from the center of the sample area
    sampleCount++;
    if (sampleHypotenuse <= .5)
    {

        circleSamples++;
    }
    m.unlock();



}

int main()
{



    int c = 0;
    while (true)
    {
        thread th1(simulate);

        th1.join();
        proportion = circleSamples / sampleCount;
        cout << setprecision(15) << proportion / pow(.5, 2) << endl;


    }

}

删除线程并直接从主线程执行模拟,尽管单线程且运行缓慢,代码仍能正常工作

0 个答案:

没有答案