从主线程传递参数给线程。当线程退出主线程都有其重置为0,为什么? [英] Passing argument from main thread to thread. When thread exits main thread has its reset to 0. Why?
问题描述
有关我们使用蒙特卡罗方法来估算PI和线程实现它一个单向分配。我的code是下方,一切似乎是,当我创建的线程结束变量numberOfPointsPerThread被重置为0。有谁知道这是为什么,除了罚款?我想每个线程都有它自己版本的栈,所以当它退出它应该离开主线程栈清楚。还是我错了?
无效* threadMonteCarlo(无效*参数)
{
INT R = 5000;
INT numberOfPointsInCircle = 0;
INT X,Y; 函数srand(时间(NULL)); 的for(int i = 0; I< *((INT *)参数);我++)
{
X =兰特()%R + 1;
Y =兰特()%R + 1;
如果(X * X + Y * Y< = R * R)
{
numberOfPointsInCircle ++;
}
} COUT<< 线程的工作<< ENDL;
了pthread_exit((void *的)numberOfPointsInCircle);
}INT主要(无效)
{
孩子的pthread_t;
INT numberOfThreads = 1;
INT numberOfPointsPerThread = 9;
INT X;
INT collectedResult;
双PI; 在pthread_create(安培;儿童,NULL,threadMonteCarlo,(无效*)及numberOfPointsPerThread);
在pthread_join(子,(无效**)及x)的;
COUT<< 从线程返回值是<< X - LT;< ENDL; collectedResult = X; COUT<< numberOfPointsPerThread =&所述;&下; numberOfPointsPerThread<< ENDL; PI = 4 *双(collectedResult)/双(numberOfPointsPerThread * numberOfThreads); COUT<< 圆周率的估计是<< PI<< ENDL; 返回0;
}
您的问题是, X
是 INT
这是不是大到足以容纳无效*
正在被写入到在pthread_join()
电话:
在pthread_join(儿童,(无效**)及X);
未定义行为所导致的明显捣毁 numberOfPointsPerThread
。
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;
}
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);
The undefined behavior that results is apparently trashing numberOfPointsPerThread
.
这篇关于从主线程传递参数给线程。当线程退出主线程都有其重置为0,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!