1

我正在尝试用 C 语言开发一个程序,它将生成给定数量的随机整数。它应该使用给定数量的线程来加快速度。我发现常规随机函数不适用于线程,现在我使用 random_r 代替。我在 initstate_r 函数中不断收到 SegFault,这没有意义,因为我正在尝试初始化变量,而不是访问它们。谁能告诉我我在这里做错了什么?(initstate_r 函数需要留在 generateRandomNumbers 函数中。)

这是代码:

#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>  // must include stdio  for pvm3.h to compile correctly
#include <sys/times.h> /* for times system call */
#include <sys/time.h>  /* for gettimeofday system call */
#include <pthread.h>

/*#define DEBUG 1*/

#define RANDOM_SEED   12345678 

//The main work routine
//void generateRandomNumbers(long long);  
void *generateRandomNumbers(void *);
double getMilliSeconds();

/* The main work routine */
//void generateRandomNumbers(long long int count)  
void *generateRandomNumbers(void *arg)
{
    struct random_data buf;
    int32_t result;
    char rand_statebuf;
    printf("hold 1\n");
    // This is the function that gives me a SegFault
    initstate_r(RANDOM_SEED, &rand_statebuf, 128, &buf);
    printf("hold 2\n"); 

    long long int* count = (long long int*) arg;
    //printf("Count for thread ID# %ld is %lld\n", pthread_self(), *count);
    long long int i;
    //long int x;

    srandom_r(RANDOM_SEED, &buf);
    for (i = 0; i < *count; i++) {
        random_r(&buf, &result);
#ifdef DEBUG
        printf("%ld\n", result);
#endif
    }
    pthread_exit(NULL);
}


int main(int argc, char **argv)
{
    long long int count, newCount;
    int numThreads;
    //pthread_t *tids;

    double timeStart = 0;
    double timeElapsed = 0;

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <n>\n" ,argv[0]);
        exit(1);
    }
    sscanf(argv[1],"%lld",&count); /* lld for long long int */
    sscanf(argv[2],"%d",&numThreads);
    pthread_t tids[numThreads];
    newCount = count/numThreads;

    timeStart = getMilliSeconds();  //And we are off

    int i;
    for (i=0; i<numThreads; i++)
    {
        pthread_create(&tids[i], NULL, generateRandomNumbers, (void *) &newCount);
    //pthread_join(tids[i], NULL);
    }

    int j;
    for (j=0; j<numThreads; j++)
    {
        pthread_join(tids[j], NULL);
    }

    //generateRandomNumbers(count);
    printf("generated %lld random numbers\n", count);

    timeElapsed = getMilliSeconds() - timeStart;
    printf("Elapsed time:  %lf seconds\n",(double)(timeElapsed/1000.0));
    fflush(stdout);

    exit(0);
}
4

1 回答 1

2

问题是,initstate_r 的第二个参数应该是一个 char*,

你做:

char rand_statebuf;
printf("hold 1\n");
// This is the function that gives me a SegFault
initstate_r(RANDOM_SEED, &rand_statebuf, 128, &buf);

您将一个指向 1 个字符的指针传递给它,它满足字符指针的要求,但是您需要的空间远不止一个字符。它应该是:

char rand_statebuf[128];
initstate_r(RANDOM_SEED,rand_statebuf,sizeof(rand_statebuf),&buf);
于 2013-08-05T19:36:35.207 回答