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

「ドローポイント」関数では、メモリを割り当てずに「カウンター」ポインターを返しています。そして、メインのタイプキャストでは、int ポインターへの void ポインター。このような

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

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

~
~

于 2013-12-10T13:31:59.723 に答える