230k views
4 votes
Write a C program that creates two threads to run the Fibonacci and the Runner processes. Threads will indicate the start and the end of their work by printing statements in the format "Thread K Starting" "Thread K Finished", where K is the thread number. When the threads finish, the parent thread will output the results generated by the two threads by printing in the format, "The sum of first 5 numbers is: 15" and "The first 5 numbers in the Fibonacci sequence are: 0, 1, 1, 2, 3" if the user had input 5 as the value of N.

User Joco
by
8.2k points

1 Answer

4 votes

Answer:

see explaination

Step-by-step explanation:

#include <pthread.h>

#include <stdio.h>

int sumOfN = 0;

int arr[1000];

int n;

void * findSumOfN(void *a){

printf("Thread 1 Starting\\");

sumOfN = (n * (n+1)) / 2; //finds sum of first n natural numbers

printf("Thread 1 Finished\\");

pthread_exit(0);

}

void * fibonacci(void *a){

printf("Thread 2 Starting\\");

arr[0]=0;

arr[1]=1;

for(int i=2;i<n;i++) //find fibonacci numbers iteratively

arr[i]=arr[i-1]+arr[i-2];

printf("Thread 2 Finished\\");

pthread_exit(0);

}

int main(void){

printf("Please enter the value of n \\");

scanf("%d", &n);

if (n <= 0)

{

printf("Wrong input ! \\"); //input validation

return 0;

}

pthread_t thread1, thread2;

pthread_create(&thread1,NULL, findSumOfN, NULL); //Create threads

pthread_create(&thread2,NULL, fibonacci, NULL);

pthread_join(thread1,NULL); //Start threads

pthread_join(thread2, NULL);

printf("The sum of first %d numbers is : %d \\",n, sumOfN);

printf("The first %d fibonacci numbers are : \\",n);

for (int i = 0; i < n; ++i)

{

printf("%d ", arr[i]);

}

printf("\\");

return(0);

}

User Ed Chin
by
8.1k points