【发布时间】:2016-03-25 16:22:35
【问题描述】:
对于 uni 赋值,我们必须使用 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;
}
【问题讨论】:
-
你确定你的意思不是
numberOfPointsInCircle被重置为零吗?这对我来说很有意义。 -
为什么在调用
pthread_exit()时将整数转换为指针?你的意思是(void*)&numberOfPointInCircle? -
当我 cout
-
好的@williamRosenbloom 我明白你的意思了。如何将 numberOfPointsInCircle 的值返回到主线程?我假设它知道零,因为该线程的堆栈不再存在。
-
@user3223954 你可以
malloc它(不推荐)或者你可以将一个指向numberOfPointsInCircle的指针传递给你的线程并调整它的值而不是返回它。同样,我会推荐后者。
标签: c++ multithreading arguments pthreads