(2)利用忙等待、互斥量及条件变量来编写求∏值的Pthreads程序
时间: 2024-05-19 13:11:15 浏览: 45
Program using Pthreads
3星 · 编辑精心推荐
以下是一个利用忙等待、互斥量及条件变量来编写求∏值的Pthreads程序的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 4
#define N 1000000000
double pi = 0.0;
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 0;
void *calc_pi(void *id) {
long tid = (long)id;
double sum = 0.0;
for (int i = tid * N / NUM_THREADS; i < (tid + 1) * N / NUM_THREADS; i++) {
double x = (double)i / N;
sum += 4.0 / (1.0 + x * x);
}
pthread_mutex_lock(&mutex);
pi += sum;
count++;
if (count == NUM_THREADS) {
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
clock_t start_time = clock();
for (long i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, calc_pi, (void *)i);
}
pthread_mutex_lock(&mutex);
while (count < NUM_THREADS) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
pi /= N;
printf("Pi = %.10f\n", pi);
printf("Time taken: %.2fs\n", (double)(clock() - start_time) / CLOCKS_PER_SEC);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
}
该程序中,首先定义了四个线程,每个线程计算一定范围内的和,然后将结果加入到全局变量pi中。使用互斥量和条件变量来保证所有线程都完成计算后才能够计算出最终的结果。最后释放互斥量和条件变量,并退出所有线程。
阅读全文