rand_r (unsigned int *seed)函数的实现

 

 

                    rand_r(unsigned int *seed)函数的实现

 

int rand_r (unsigned int *seed)
{
 unsigned int next = *seed;
 int result;

 next *= 1103515245;
 next += 12345;
 result = (unsigned int) (next / 65536) % 2048;

 next *= 1103515245;
 next += 12345;
 result <<= 10;
 result ^= (unsigned int) (next / 65536) % 1024;

 next *= 1103515245;
 next += 12345;
 result <<= 10;
 result ^= (unsigned int) (next / 65536) % 1024;

 *seed = next;

 return result;
}

 

 

 

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <math.h> #include <sys/time.h> #define NUM_THREADS 4 #define TOTAL_POINTS 10000000 #define REPORT_INTERVAL 1000 pthread_mutex_t mutex; int total_points_in_circle = 0; int total_points_generated = 0; void* generate_points(void* arg) { int points_in_circle = 0; struct timeval tv; gettimeofday(&tv, NULL); unsigned int seed = tv.tv_sec ^ tv.tv_usec ^ pthread_self(); while (1) { pthread_mutex_lock(&mutex); if (total_points_generated >= TOTAL_POINTS) { pthread_mutex_unlock(&mutex); break; } total_points_generated++; pthread_mutex_unlock(&mutex); double x = (double)rand_r(&seed) / RAND_MAX * 2 - 1; double y = (double)rand_r(&seed) / RAND_MAX * 2 - 1; if (sqrt(x*x + y*y) <= 1) { points_in_circle++; } if (total_points_generated % REPORT_INTERVAL == 0) { pthread_mutex_lock(&mutex); total_points_in_circle += points_in_circle; printf("Points: (%d,%d)\n", x,y); pthread_mutex_unlock(&mutex); points_in_circle = 0; } } pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int i; struct timeval start_time, end_time; pthread_mutex_init(&mutex, NULL); gettimeofday(&start_time, NULL); // 获取程序开始时间 for (i = 0; i < NUM_THREADS; i++) { pthread_create(&threads[i], NULL, generate_points, NULL); } for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } gettimeofday(&end_time, NULL); // 获取程序结束时间 pthread_mutex_destroy(&mutex); double pi = 4.0 * total_points_in_circle / TOTAL_POINTS; printf("Estimated value of pi: %lf\n", pi); // 计算程序运行时间 double execution_time = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_usec - start_time.tv_usec) / 1000000.0; printf("Execution time: %lf seconds\n", execution_time); return 0; }给这段程序每一句后加上注释
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值