98.7k views
0 votes
Write a multithreaded program that generates the Fibonacci series using Pthreads thread library. This program should work as follows: The user will enter on the command line the number of Fibonacci numbers that the program is to generate (* in this case 7 *). The program will then create a separate thread that will generate the Fibonacci sequence, placing the sequence in data-code (section) that is shared by the threads (an array isprobably the most convenient data structure). When the thread finishes execution, the parent thread will output the sequence generated by the child thread. Because the parent thread cannot begin outputting the Fibonacci sequence until the child thread finishes, this will require having the parent thread wait for the child thread.

User Yonigozman
by
5.1k points

1 Answer

7 votes

Answer:

#include <pthread.h>

#include <stdio.h>

#include <stdlib.h>

pthread_mutex_t mutex;

int fib[10]; /* this data is shared by the thread(s) */

int in = 0;

void *genFibo(void *param); /* the thread */

int main(int argc, char *argv[])

{

pthread_attr_t attr;

if (argc != 2) {

fprintf(stderr,"usage: fibthread <integer value>\\");

return -1;

}

int count = atoi(argv[1]);

if (count < 1) {

fprintf(stderr,"%d must be>= 1\\", count);

return -1;

}

pthread_attr_init(&attr);

// Mutex Lock

pthread_mutex_init(&mutex, NULL);

// each thread computes fibonacci

for(int i = 1;i <= count;i++) {

pthread_t thread;

pthread_create(&thread, &attr, genFibo, (void*)i);

pthread_join(thread, NULL);

}

// print resulting array

for (int i = 0; i < in;i++) {

printf("%d ", fib[i]);

}

printf("\\");

pthread_mutex_destroy(&mutex);

}

void *genFibo(void *param)

{

pthread_mutex_lock(&mutex);

fib[in++] = fibonacci((int)param);

pthread_mutex_unlock(&mutex);

pthread_exit(0);

}

int fibonacci (int x)

{

if (x <= 1) {

return 1;

}

return fibonacci(x-1) + fibonacci(x-2);

}

User Sherard
by
4.2k points