I need help writing a c program to run in Unix that uses pthread library to create a thread that computes the fibonacci numbers. I should provide a parameter to the thread indicating which fibonacci number to return and use pthread_join to wait and collect the returned value and lastly print it.
/*
Operating Systems
October 13th, 2010 */
#include <pthread.h>
#include <stdio.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>\n");
return -1;
}
if (atoi(argv[1]) < 0)
{
fprintf(stderr,"Argument %d must be non-negative\n",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\n",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 \n");
printf("%d\n",pre1);
exit(0);
}
else
if (fib == 2)
{
printf("The Fibonacci sequence for the number you entered is \n");
printf("%d , %d\n",pre1 ,pre2 );
exit(0);
}
else
{ int j=3;
printf(" \nThe Fibonacci sequence for the number you entered is \n %d , %d ,",pre1,pre2 );
for(j = 3; j <= fib; j++)
{
current = pre2 + pre1;
pre1 = pre2;
pre2 = current;
printf(" %d ,",current);
}
}
}
pthread_exit(0);
}
*/
("Foo\n");