我一直试图通过valgrind泄漏检查,并通过20亿个随机数字并将它们在线程之间分开。一旦我得到10亿个随机数,我会一直收到seg错误。我在哪里分配错误或我做错了什么?c中使用线程安全随机数的多线程
struct thread
{
long long int threadID; //The thread id
long long int operations; //The number of threads
};
void *generateThreads(void *ptr)
{
struct thread *args = ptr;
struct random_data *rdata = (struct random_data *) calloc(args->operations*64,sizeof(struct random_data));
char *statebuf = (char*) calloc(args->operations*64,BUFSIZE);
long long int i;
int32_t value;
for(i = 0; i < args->operations; i++)
{
initstate_r(args->threadID,&statebuf[i],BUFSIZE,&rdata[i]);
random_r(rdata,&value);
}
if(DEBUG > 1)
printf("I am thread %lld with thread id %X\n", args->threadID, (unsigned int) pthread_self());
free(rdata);
free(statebuf);
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
long long int numRandoms;
long long int numThreads;
double timeStart = 0;
double timeElapsed = 0;
pthread_t *tid;
struct thread args;
if (argc != 3)
{
fprintf(stderr, "Usage: %s \n" ,argv[0]);
exit(1);
}
/* Assign the arg values to appropriate variables */
sscanf(argv[1],"%lld",&numRandoms); /* lld for long long int */
sscanf(argv[2],"%lld",&numThreads); /* lld for long long int */
/* Number of threads must be less than or equal to the number of random numbers */
if(numRandoms < numThreads)
{
fprintf(stderr,"Number of threads must be less than or equal to the number of random numers.\n");
exit(1);
}
/*Start*/
long long int i;
args.operations = numRandoms/numThreads;
timeStart = getMilliSeconds();
tid = (pthread_t *) calloc(numThreads,sizeof(pthread_t));
/* value is the thread id, creating threads */
for(i = 0; i < numThreads; i++)
{
args.threadID = i;
pthread_create(&tid[i],NULL,generateThreads,(void *) &args);
}
/* Joining the threads */
for(i = 0; i < numThreads; i++)
{
pthread_join(tid[i],NULL);
}
/*Output*/
timeElapsed = getMilliSeconds() - timeStart;
printf("%lf\n",(double)(timeElapsed/1000.0));
free(tid);
fflush(stdout);
exit(0);
}
+1
你还没两种变异来源播种” t向我们展示了什么'struct random_data',所以我们不知道它有多大。但是,'calloc()'的参数很可能超过了您可以在您的计算机上以单个块分配的大小。另一个重要的问题是:你是否将其构建为32位或64位程序? –
2014-12-05 00:45:00
+0
你不能随机生成随机数吗? 'rand()'返回一个15位的数字,但你可以通过例如'r = rand()+(rand()<< 15)轻松获得更大的数字;' –
2014-12-05 00:58:42
+0
(off-topic)不是线程数量长久的矫枉过正?我知道有些人想让他们的代码有前途的证据。 –
2014-12-05 02:11:46