2026-01-19 22:25:53 +08:00

72 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define NUM_THREADS 4
long long num_steps = 1000000000;
double step;
double global_sum = 0.0;
pthread_mutex_t mutex;
void *compute_pi(void *arg) {
int thread_id = *(int *)arg;
double local_sum = 0.0;
long long start = thread_id * (num_steps / NUM_THREADS);
long long end = (thread_id + 1) * (num_steps / NUM_THREADS);
if (thread_id == NUM_THREADS - 1) end = num_steps; // Handle remainder
for (long long i = start; i < end; i++) {
double x = (i + 0.5) * step;
local_sum += 4.0 / (1.0 + x * x);
}
pthread_mutex_lock(&mutex);
global_sum += local_sum;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(int argc, char* argv[])
{
struct timeval TimeStampStart, TimeStampStop;
double ExeTime;
double pi;
int thread_ids[NUM_THREADS];
pthread_t threads[NUM_THREADS];
step = 1.0 / (double)num_steps;
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
gettimeofday(&TimeStampStart, NULL);
// Create threads
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, compute_pi, &thread_ids[i]);
}
// Wait for threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pi = global_sum * step;
gettimeofday(&TimeStampStop, NULL);
ExeTime = (double)(TimeStampStop.tv_sec - TimeStampStart.tv_sec) +
(double)(TimeStampStop.tv_usec - TimeStampStart.tv_usec) * 1e-6;
// Destroy mutex
pthread_mutex_destroy(&mutex);
printf("The value of PI is %15.12f\n", pi);
printf("The time to calculate PI was %f seconds\n", ExeTime);
return 0;
}