C++ 正在收集从线程返回的结果

C++ 正在收集从线程返回的结果,c++,linux,multithreading,pthreads,C++,Linux,Multithreading,Pthreads,为uni做一个赋值,我们需要使用线程来近似pi。线程对圆内的点进行计数,完成后返回结果。主线程需要收集这些结果并运行一个等式。一切似乎都在正常工作,除了我不能添加到我收集的结果,它只是输出与线程返回值相同的结果。有什么想法吗 #include <iostream> #include <stdlib.h> #include <time.h> #include <pthread.h> using namespace std; void * thre

为uni做一个赋值,我们需要使用线程来近似pi。线程对圆内的点进行计数,完成后返回结果。主线程需要收集这些结果并运行一个等式。一切似乎都在正常工作,除了我不能添加到我收集的结果,它只是输出与线程返回值相同的结果。有什么想法吗

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

using namespace std;

void * threadMonteCarlo(void * param)
{
    int r = 10000;
    int numberOfPointsInCircle = 0; 
    int x, y;

    srand(time(NULL));

    for(int i=0; i<*((int *) param); i++)
    {
        x = rand() % r + 1;
        y = rand() % r + 1;
        if (x*x + y*y <= r*r)
        {
            numberOfPointsInCircle++;
        }
    }   
    cout << "In this thread the points found inside the circle were: " << numberOfPointsInCircle << endl;
    pthread_exit((void *)numberOfPointsInCircle);
}

int main(void)
{
    int numberOfThreads = 4;
    pthread_t thread[numberOfThreads];

    int numberOfPointsPerThread = 1000000000/numberOfThreads;
    int collectedResult = 0;
    int x = 0;

    double pi;

    for(int i=0; i<numberOfThreads; i++)
    {
        pthread_create(&thread[i], NULL, threadMonteCarlo, (void *)&numberOfPointsPerThread);
    }

    for(int i=0; i<numberOfThreads; i++)
    {
        collectedResult = collectedResult + x;
        cout << "The total result is: " << collectedResult << endl;
        pthread_join(thread[i], (void **)&x);
        cout << "The retrieved result was " << x << endl;
    }

    pi = 4*double(collectedResult)/(numberOfPointsPerThread*numberOfThreads);

    cout << "Estimate of pi is " << pi << endl;

    return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
void*threadMonteCarlo(void*param)
{
int r=10000;
int numberOfPointsInCircle=0;
int x,y;
srand(时间(空));

对于(int i=0;i同一代码的@EOF可能存在重复项)不同的问题。您尚未修复旧问题答案中指出的未定义行为。只要程序显示未定义行为,就不可能有合理的新答案。