In: Computer Science
PART B: Computing Fibonacci Numbers With Threads
This programming project is based on a problem given in our textbook. The Fibonacci sequence is the series of numbers 0, 1, 1, 2, 3, 5, 8,.... Formally, it can be expressed as: fib0 = 0 fib1 = 1 fibn = fibn-1 + fibn-2 Write a multithreaded program that generates the Fibonacci series using the pThreads library. This program should work as follows: The user will enter on the command line the number of Fibonacci numbers that the program will generate. The program will then create a separate thread that will generate the Fibonacci numbers placing the sequence in data that is shared by the threads (an array or vector is probably 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 to finish, using the techniques discussed in the class
SOLUTION-
I have solve the problem in C code with comments and screenshot for
easy understanding :)
CODE-
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include<pthread.h>
#include<errno.h>
#include <stdlib.h>
#include <signal.h>
int fib0[100];
int fib1[100];
int fib2[100];
void *myThreadFun0(void *vargp)
{
int *p = (int *)vargp;
fib0[0] = 0;
fib0[1] = 1;
int l;
//printf("%d\n",*p);
for (l = 2; l<*p; l++){
fib0[l] = fib0[l-1]+
fib0[l-2];
}
return NULL;
}
void *myThreadFun1(void *vargp)
{
int *p = (int *)vargp;
fib1[0] = 0;
fib1[1] = 1;
int l;
//printf("%d\n",*p);
for (l = 2; l<*p; l++){
fib1[l] = fib1[l-1]+
fib1[l-2];
}
return NULL;
}
void *myThreadFun2(void *vargp)
{
int *p = (int *)vargp;
fib2[0] = 0;
fib2[1] = 1;
int l;
//printf("%d\n",*p);
for (l = 2; l<*p; l++){
fib2[l] = fib2[l-1] +
fib2[l-2];
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t *tid;
tid = (pthread_t *)malloc(sizeof(pthread_t) *
atoi(argv[1]));
int *count = (int *) malloc(sizeof(int) *
atoi(argv[1]));
int i;
int n = atoi(argv[1]);
int j = n-1;
int k = n+ 1;
pthread_create(&tid[0], NULL,
myThreadFun0, &n);
pthread_create(&tid[1], NULL, myThreadFun1,
&j);
pthread_create(&tid[2], NULL, myThreadFun2,
&k);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
printf("Sequence by thread1:\n");
for (i = 0; i<n; i++){
printf("%d ", fib0[i]);
}
printf("\n");
printf("Sequence by thread2:\n");
for (i = 0; i<j; i++){
printf("%d ", fib1[i]);
}
printf("\n");
printf("Sequence by thread3:\n");
for (i = 0; i<k; i++){
printf("%d ", fib2[i]);
}
printf("\n");
exit(0);
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------