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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值