문제

I'm trying to calculate the value of pi using multiple threads in ubuntu using c. I'm not perfectly familiar with the variables that the pthread_create and pthread_join should get as input, as well as how to deal with type 'void'. I planted some printf's along the code in order to locate the source of the problem and apparently the problem is in the 'pthread_join' in the last 'for loop' in the main()

this is my code:

#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;

}

this is the log I get in Terminal:

3079416688
try

Segmentation fault
도움이 되었습니까?

해결책

from your function 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 

So before you dereference counter you have to run something like this:

int* counter = malloc(sizeof(int));

and check whether couter != NULL.

Also than you need to make sure you free it as well after use.

다른 팁

In you "drawpoints" function, you are returning "counter" pointer without allocating any memory to it. And in main typecast void pointer to int pointer. like this

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

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

~
~

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top