Write a multithreaded program in c of the fibonacci sequence using the Win32 thr
ID: 3731753 • Letter: W
Question
Write a multithreaded program in c of the fibonacci sequence using the Win32 thread.
The user will enter on the command line the number of Fibonacci numbers that the program is to generate. The program will then create a separate thread that will generate the Fibonacci numbers, placing the sequence in data that can be shared by the threads (an array 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 described in Section 4.3 for the textbook.
Explanation / Answer
/* Code for Fibonacci with wait and join */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fib; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
int main(int argc, char *argv[])
{
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of attributes for the thread */
if (argc != 2) {
fprintf(stderr,"usage: a.out <integer value> ");
return -1;
}
if (atoi(argv[1]) < 0)
{
fprintf(stderr,"Argument %d must be non-negative ",atoi(argv[1]));
return -1;
}
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]);
/* now wait for the thread to exit */
pthread_join(tid,NULL);
printf("Fibonacci = %d ",fib);
}
/**
* The thread will begin control in this function
*/
void *runner(void *param)
{
int i, upper = atoi(param);
fib= 1;
if (upper > 0)
{
int pre1 = 0;
int pre2 = 1;
int current ;
if (fib == 1)
{
printf("The Fibonacci sequence for the number you entered is ");
printf("%d ",pre1);
exit(0);
}
else
if (fib == 2)
{
printf("The Fibonacci sequence for the number you entered is ");
printf("%d , %d ",pre1 ,pre2 );
exit(0);
}
else
{ int j=3;
printf(" The Fibonacci sequence for the number you entered is %d , %d ,",pre1,pre2 );
for(j = 3; j <= fib; j++)
{
current = pre2 + pre1;
pre1 = pre2;
pre2 = current;
printf(" %d ,",current);
}
}
}
pthread_exit(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.