I'm trying to thread a monte carlo simulation to calculate pi. I need each thread to generate 2 random numbers (x and y values between 1 and 0) to sample the simulation, as of now, i'm trying to get one thread to work, but it keeps generating the same number.

#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));


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



int main()

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

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



Removing the thread and executing simulate directly from the main thread, the code works perfectly fine, albeit single threaded and slow

0 Answers