我試圖計算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
需要初始化指針變量。 – zch
嘗試使用-Wall -Wextra編譯你的程序,它會顯示你一些問題。您可以在gdb下運行該程序來調查導致段錯誤的原因。如果添加-g作爲編譯標誌,將包括調試符號。 – Silas