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");

Dani AI

Generated

You are running into two separate issues: returning a value from a pthread, and off-by-two indexing. Define the sequence explicitly as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2). In your Post #3 you return from inside the loop on the first iteration, and in Post #4 you start with 1,1 which shifts the index. Also, do not cast an int to a void* for the return; either write into caller-owned memory or allocate space for the result and return that pointer. Finally, ’s link errors are from not linking against pthreads; use -pthread (recommended) or -lpthread as noted.

Below is a compact pattern that passes the index n to a worker thread, waits with pthread_join, collects the returned value, prints it, and frees memory. It handles n=0 and n=1 correctly and avoids overflow by limiting to 0..93 for uint64_t.

#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

struct fib_arg { unsigned int n; };

static void* fib_worker(void* p) {
    struct fib_arg* a = (struct fib_arg*)p;
    uint64_t* out = malloc(sizeof *out);
    if (!out) pthread_exit(NULL);
    if (a->n == 0) { *out = 0; pthread_exit(out); }
    uint64_t f0 = 0, f1 = 1;
    for (unsigned i = 2; i <= a->n; ++i) { uint64_t t = f0 + f1; f0 = f1; f1 = t; }
    *out = f1; pthread_exit(out);
}

int main(int argc, char** argv) {
    if (argc != 2) { fprintf(stderr, "usage: %s <n:0..93>\n", argv[0]); return 1; }
    char* end; unsigned long ul = strtoul(argv[1], &end, 10);
    if (*end || ul > 93) { fprintf(stderr, "n must be 0..93\n"); return 1; }

    struct fib_arg a = { .n = (unsigned)ul };
    pthread_t th; if (pthread_create(&th, NULL, fib_worker, &a)) return 1;
    void* ret = NULL; if (pthread_join(th, &ret)) return 1;
    if (!ret) return 1; uint64_t val = *(uint64_t*)ret; free(ret);

    printf("F(%u) = %llu\n", a.n, (unsigned long long)val);
    return 0;
}

Build and run:

  • gcc -std=c11 -O2 -Wall -Wextra -pthread fib.c -o fib
  • ./fib 10 -> F(10) = 55

Tips:

  • Do not call exit() from a thread; return or use pthread_exit.
  • If you still see a 2-ahead result, you started from 1,1 instead of 0,1.

Recommended Answers

All 5 Replies

Hi everyone, this is what I have gotten so far, but it keeps giving me an error
" fibon.c:(.text+0x65): undefined reference to `fibonacci'
collect2: ld returned 1 exit status"

How can I fix this?

Again, the program supposed to calculate fibonacci and indicate which fibonacci number to return. Also, the program should use the pthread_join to wait and collect the number returned value and then print it.

Please help me!

#include <pthread.h>
#include <stdio.h>

/* compute successive prime numbers. return the nth prime number where n is the$*/

void* fibonacci(void* arg);
main()
{

        pthread_t thread;
        int num1 = 0;
        int num2 = 1;;
        int ans;
        int i;

        int counter, numPrint;
        numPrint = 10;

        for(counter= 0; counter < numPrint; ++counter){
      ans = (num1 + num2);
                num1 = num2;
                num2 = ans;
        }


        /* start the computing thread, up to the 20th number */
        pthread_create(&thread, NULL, &fibonacci, (void*)&numPrint);

        /* wait for the fibonacci thread to complete */
         pthread_join(thread, (void*)&ans);

        /* print the number in the position requested */
        printf("the  number is %d.\n", ans);

 }

Newer version. Now it seems like it only prints the result do the addition of the firt 2 numbers. Can anyone please tell me what I am doing wrong?

Thank you

#include <pthread.h>
#include <stdio.h>

/* compute sucessive fibonnaci numbers.*/

void* fibonacci(void* arg){
        int num1 = 1;
        int num2 = 1;;
        int ans;
        int maxfibo=10;

        int counter, numPrint;
        for(counter= 0; counter < maxfibo; ++counter){

                ans = (num1 + num2);
                num1 = num2;
                num2 = ans;
        return (void*) ans;
        }
}
int main ()
{
        pthread_t thread;
        int number;
        int which_fibo = 1;

        /* start the computing thread up to the number you want to return*/
        pthread_create(&thread, NULL, &fibonacci, (void*)&which_fibo);

        /* wait for the fibonacci thread to complete */
         pthread_join(thread, (void*)&number);

        /* print the number in the position requested */
        printf("The number is %d.\n", number);

        return 0;

 }

Some progress...Now my program is printing 2 positions ahead. For exemplo:

0 1 1 2 3 5 8 13

If I select to print position 3, the result would be 3.
If I select to print position 4, the result would be 5.ow

How can I fix this problem, and how can I return the value if the position selected is 1 or 2?

#include <pthread.h>
#include <stdio.h>

/* compute sucessive fibonnaci numbers.*/

void* fibonacci(void* arg){
int num1 = 1;
int num2 = 1;;
int ans;
int maxfibo=10;
int n = *((int*) arg);
int is_num = 1;

int counter;

for(counter= 0; counter < (maxfibo-2); ++counter){

ans = (num1 + num2);
num1 = num2;
num2 = ans;
if (is_num) {
if (--n==0)
return (void*) ans;
}
}
}
int main ()
{
pthread_t thread;
int which_fibo = 5;
int number;


/* start the computing thread up to the number you want to return*/
pthread_create(&thread, NULL, &fibonacci, (void*)&which_fibo);

/* wait for the fibonacci thread to complete */
pthread_join(thread, (void*)&number);



/* print the number in the position requested */
printf("The number is %d.\n", number);

return 0;

}
r.c: In function ‘runner’:
r.c:81:6: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
r.c:89:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
/tmp/ccwR2niK.o: In function `main':
r.c:(.text+0xd9): undefined reference to `pthread_create'
r.c:(.text+0xea): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

: Try using a dictionary/look-up table approach. Create a table where you plug in the first two spots (0 and 1). Then have your program plug in the data if it isn't already assigned. You might want to fill the table with -1's at first, then assign the first two spots. If a table location holds a -1, your program will know that spot hasn't been assigned yet and needs to be calculated.

@IntermediateTech: You have to compile in the Posix Threads library. If you're using GCC, you'll want to use the -lpthread option.

EDIT: I suddenly realized this was a necro-thread. /facepalm

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.