我正在尝试使用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
答案 0 :(得分:1)
drawpoints
的:
int* counter; //You don't allocate memory for this int
double x,y,dist; /*coordinates of point*/
int* n = arg
*counter = 0; //yet here you assign 0 to a unknown memory location
因此,在你取消引用计数器之前,你必须运行这样的东西:
int* counter = malloc(sizeof(int));
并检查是否couter!= NULL。
除了你需要确保你在使用后也释放它。
答案 1 :(得分:1)
在“drawpoints”函数中,您返回“计数器”指针而不向其分配任何内存。 并且在主要的类型转换中指向int指针的void指针。 像这样
int* counter=NULL;
counter = (int *)malloc(sizeof(int));
if(NULL == count)
return -1;
//typecast
curr = ((int *)currPtr);
〜
〜