用pthread_create和pthread_join 写一个多线程版本的斐波那契
时间: 2023-09-16 16:08:25 浏览: 135
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_N 100
int fib[MAX_N+1];
void* fib_thread(void* n_pointer) {
int n = *(int*)n_pointer;
if (n <= 1) {
fib[n] = n;
} else {
pthread_t thread1, thread2;
int n1 = n - 1;
int n2 = n - 2;
pthread_create(&thread1, NULL, fib_thread, &n1);
pthread_create(&thread2, NULL, fib_thread, &n2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
fib[n] = fib[n1] + fib[n2];
}
pthread_exit(0);
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
if (n < 0 || n > MAX_N) {
printf("n must be between 0 and %d\n", MAX_N);
exit(1);
}
pthread_t thread;
pthread_create(&thread, NULL, fib_thread, &n);
pthread_join(thread, NULL);
printf("Fibonacci(%d) = %d\n", n, fib[n]);
return 0;
}
阅读全文