赞
踩
我一直試圖通過檢查,並且傳遞 2億個隨機數,並在線程之間劃分它們。 一旦達到 1億個隨機數我一直得到一個錯誤。 我在哪裡分配錯誤或者我做錯了什麼?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 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 %Xn", 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
{
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
{
args.threadID = i;
pthread_create(&tid[i],NULL,generateThreads,(void *) &args);
}
/* Joining the threads */
for(i = 0; i
{
pthread_join(tid[i],NULL);
}
/*Output*/
timeElapsed = getMilliSeconds() - timeStart;
printf("%lfn",(double)(timeElapsed/1000.0));
free(tid);
fflush(stdout);
exit(0);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。