修改以下代码:#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <math.h> #define MAX_THREADS 8 double a, b, h; int n, thread_count; double total_sum = 0; void* Trap(void* rank) { long my_rank = (long) rank; double local_a = a + my_rank * n * h / thread_count; double local_b = local_a + n * h / thread_count; double local_sum = (pow(local_a, 2) + pow(local_b, 2)) / 2.0; for (int i = 1; i < n / thread_count; i++) { double x = local_a + i * h; local_sum += pow(x, 2); } local_sum *= h; total_sum += local_sum; return NULL; } int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; a = 0.0; b = 1.0; n = 1000000; thread_count = (int) strtol(argv[1], NULL, 10); h = (b - a) / n; thread_handles = (pthread_t*) malloc(thread_count * sizeof(pthread_t)); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], NULL, Trap, (void*) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } printf("With n = %d trapezoids, our estimate\n", n); printf("of the integral from %f to %f = %.15f\n", a, b, total_sum); free(thread_handles); return 0; }
时间: 2023-12-10 15:38:13 浏览: 164
以下是修改后的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#define MAX_THREADS 8
double a, b, h;
int n, thread_count;
double total_sum = 0;
pthread_mutex_t mutex; // 新增互斥锁
void* Trap(void* rank) {
long my_rank = (long) rank;
double local_a = a + my_rank * n * h / thread_count;
double local_b = local_a + n * h / thread_count;
double local_sum = (pow(local_a, 2) + pow(local_b, 2)) / 2.0;
for (int i = 1; i < n / thread_count; i++) {
double x = local_a + i * h;
local_sum += pow(x, 2);
}
local_sum *= h;
pthread_mutex_lock(&mutex); // 加锁
total_sum += local_sum;
pthread_mutex_unlock(&mutex); // 解锁
return NULL;
}
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
a = 0.0;
b = 1.0;
n = 1000000;
thread_count = (int) strtol(argv[1], NULL, 10);
h = (b - a) / n;
thread_handles = (pthread_t*) malloc(thread_count * sizeof(pthread_t));
pthread_mutex_init(&mutex, NULL); // 初始化互斥锁
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], NULL, Trap, (void*) thread);
}
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], NULL);
}
printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.15f\n", a, b, total_sum);
free(thread_handles);
pthread_mutex_destroy(&mutex); // 销毁互斥锁
return 0;
}
```
修改说明:
1. 新增了一个互斥锁 `pthread_mutex_t mutex`,以保证多个线程同时修改 `total_sum` 时不会出现竞争问题。
2. 在 `Trap` 函数里面,将 `total_sum += local_sum` 的操作放在加锁和解锁之间,以保证只有一个线程可以修改 `total_sum`。
3. 在 `main` 函数中,新增了互斥锁的初始化 `pthread_mutex_init(&mutex, NULL)` 和销毁 `pthread_mutex_destroy(&mutex)` 操作。
阅读全文