700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > c语言多线程编程随机数 在c 中使用线程安全的随机数 多线程_c_开发99编程知识库...

c语言多线程编程随机数 在c 中使用线程安全的随机数 多线程_c_开发99编程知识库...

时间:2023-04-08 07:04:41

相关推荐

c语言多线程编程随机数 在c 中使用线程安全的随机数 多线程_c_开发99编程知识库...

我一直試圖通過檢查,並且傳遞 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);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。