我正在尝试使用 c 在 ubuntu 中使用多个线程计算 pi 的值。我并不完全熟悉 pthread_create 和 pthread_join 应该作为输入的变量,以及如何处理类型“void”。我在代码中植入了一些 printf,以便找到问题的根源,显然问题出在 main() 中最后一个“for 循环”中的“pthread_join”中
这是我的代码:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <pthread.h>
void* drawpoints (void* arg)
{
int i;
int* counter;
double x,y,dist; /*coordinates of point*/
int* n = arg;
*counter = 0;
srand(time(NULL));
for (i = 0; i<*n; i++)
{
/*square is of size 1X1 - 0<=x,y<=1 -> radius = 0.5*/
x = (double)rand()/(double)RAND_MAX;
y = (double)rand()/(double)RAND_MAX;
/*0.5 is the center of circle*/
dist = sqrt(pow(x-0.5,2)+pow(y-0.5,2));
if (dist<0.5)
{
*counter++;
}
/* printf("x = %f\ny = %f\ndist = %f\ncounter = %d\n\n",x,y,dist,*counter);*/
}
return (void*)counter;
}
int main (int argc, char** argv)
{
assert(argc == 3);
int rc;
int totalThreads,n,i,counter,numDots;
void* currPtr;
int* curr;
pthread_t* p_list = (pthread_t*)malloc(sizeof(pthread_t)*atoi(argv[2]));
n = atoi(argv[1]);
totalThreads = atoi(argv[2]);
numDots = n/totalThreads;
for (i = 0; i<totalThreads; i++)
{
rc = pthread_create(&(p_list[i]), NULL, drawpoints, &numDots); assert(rc == 0);
}
for (i = 0; i<totalThreads; i++)
{
printf("%lu\ntry\n\n",p_list[i]);
rc = pthread_join(p_list[i], &currPtr); assert(rc == 0);
curr = currPtr;
counter+=(*curr);
}
printf("%f\n\n",(double)counter/n*4);
free(p_list);
return 0;
}
这是我在终端中得到的日志:
3079416688
try
Segmentation fault