从主线程到线程传递参数.当线程退出主线程时,它会被重置为 0.为什么? [英] Passing argument from main thread to thread. When thread exits main thread has its reset to 0. Why?

查看:29
本文介绍了从主线程到线程传递参数.当线程退出主线程时,它会被重置为 0.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 uni 分配,我们必须使用蒙特卡罗方法估计 pi ​​并在线程中实现它.我的代码在下面,一切似乎都很好,除非我创建的线程结束时变量 numberOfPointsPerThread 被重置为 0.有人知道这是为什么吗?我认为每个线程都有自己的堆栈版本,因此当它退出时,它应该清除主线程堆栈.还是我错了?

For a uni assignment we have to estimate pi using the monte carlo method and implement it in threads. My code is below and everything seems to be fine except when my created thread ends the variable numberOfPointsPerThread gets reset to 0. Does anybody know why that is? I thought each thread has its own version of the stack so when it exits it should leave the main threads stack clear. Or am I wrong?

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

推荐答案

你的问题是 x 是一个 int 不够大,无法容纳 pthread_join() 调用中写入的 void* :

Your problem is that x is an int which is not large enough to hold the void* that is being written to in the pthread_join() call:

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

导致的未定义行为显然破坏了 numberOfPointsPerThread.

The undefined behavior that results is apparently trashing numberOfPointsPerThread.

这篇关于从主线程到线程传递参数.当线程退出主线程时,它会被重置为 0.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆