1

我正在尝试使用 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
4

2 回答 2

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。

此外,您还需要确保在使用后也将其释放。

于 2013-12-09T19:39:21.037 回答
1

在您的“drawpoints”函数中,您将返回“counter”指针而不为其分配任何内存。并且在主要类型转换中 void 指针指向 int 指针。像这样

int* counter=NULL;
counter = (int *)malloc(sizeof(int));
if(NULL == count)
 return -1;

//typecast
curr = ((int *)currPtr);

~~
_

于 2013-12-10T13:31:59.723 回答