2013-12-09 41 views
1

我試圖計算pi使用多個線程在ubuntu中使用c的值。 我不完全熟悉pthread_create和pthread_join應該作爲輸入的變量,以及如何處理類型'void'。 我在過去的「for循環」種了一些的printf沿碼的,以便找到問題的根源,顯然這個問題是在「在pthread_join」在main()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 
+1

需要初始化指針變量。 – zch

+0

嘗試使用-Wall -Wextra編譯你的程序,它會顯示你一些問題。您可以在gdb下運行該程序來調查導致段錯誤的原因。如果添加-g作爲編譯標誌,將包括調試符號。 – Silas

回答

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

,並檢查是否種臺!= NULL。

此外,你需要確保你釋放它以及使用後。

1

在您的「drawpoints」函數中,您正在返回「計數器」指針而不分配任何內存。 並在主類型爲void指針指向int指針。 這樣

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

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


+1

你爲什麼要引用所有的代碼。僅僅將相關部分添加到答案中是不夠的。請清理你的答案。 – alk