11) Multi Thread program in C to create and print Fibonacci series in two separate threads with proper synchronization [VTU SS&OS]

vtu ss & os 11
Code:

Explanation:
Aim of this program is to create two threads. one to generate Fibonacci numbers upto a series specified by user. another thread to print those generated Fibonacci numbers. We ensure proper synchronization between threads to ensure displaying doesn't take place before generating.

#include<stdio.h>
#include<omp.h>

Inclusion of Header files.

int fibonacci(int n)
{
if(n<2)
return n;
else
return fibonacci(n-1)+fibonacci(n-2);
}

This is the function which returns the nth Fibonacci number. 'n' is the input parameter to function. function recursively calls itself to find the nth Fibonacci number.
example:
n=3;
return fib(2)+fib(1);
return (fib(1)+fib(0))+1;
return 1+0+1;
return 2;

3rd Fibonacci number is 2.


int main()
{
int fibnumber[100],i,j,n;

printf("Please Enter the series limit\n");
scanf("%d",&n);

main function begins. input the series limit. (that is up to which fibonacci term?)
and an array to store all those Fibonacci terms with size 100.

#pragma omp parallel num_threads(2)
{

declaring number of threads to be 2. using #pragma pre processor and openmp parameter.

#pragma omp critical

for synchronization.

if(omp_get_thread_num()==0)
{
printf("There are %d threads\n", omp_get_num_threads());
printf("Thread %d generating numbers..\n", omp_get_thread_num());
for(i=0;i<n;i++)
fibnumber[i]=fibonacci(i);
}

Here omp_get_thread_num(), will return current thread number. If 0, then its first thread. we produce Fibonacci numbers here and store in array. (0-n terms using for loop).
omp_get_thread_num() function in the 3rd line of snippet will print total number of threads created.

else
{
printf("Thread %d Printing numbers..\n", omp_get_thread_num());
for(j=0;j<n;j++)
printf("%d\t", fibnumber[j]);
}
} //of outer if statement.

If its not first thread, then its obviously second thread because there are only two threads created. so we print here, the Fibonacci numbers (0-n) as per experiment.

printf("\n");
return 0;
}

This one is self explanatory.

That's it :)

He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!

Sharing is sexy!

Related Articles

Share your views about this article!