将参数从主线程传递给线程。当线程退出主线程时,它的复位为0.为什么?

时间:2015-12-18 21:45:30

标签: c++ multithreading arguments pthreads

对于单一赋值,我们必须使用monte carlo方法估计pi并在线程中实现它。我的代码在下面,一切似乎都很好,除非我创建的线程结束时变量numberOfPointsPerThread重置为0.有人知道为什么会这样吗?我认为每个线程都有自己的堆栈版本,所以当它退出时应该让主线程堆栈清晰。或者我错了吗?

void * threadMonteCarlo(void * param)
{
    int r = 5000;
    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 << "Thread working" << endl;
    pthread_exit((void*)numberOfPointsInCircle);
}

int main(void)
{
    pthread_t child;
    int numberOfThreads = 1;
    int numberOfPointsPerThread = 9;
    int x;
    int collectedResult;
    double pi;

    pthread_create(&child, NULL, threadMonteCarlo, (void *)&numberOfPointsPerThread);
    pthread_join(child, (void **)&x);
    cout << "Returning value from thread is " << x <<endl;

    collectedResult = x;

    cout << "numberOfPointsPerThread = " << numberOfPointsPerThread << endl;

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

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

    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的问题是x是一个int,其大小不足以容纳void*来电中写入的pthread_join()

pthread_join(child, (void **)&x);

结果的未定义行为显然是在废弃numberOfPointsPerThread