Write a multithreaded program that generates the Fibonacci sequence using either
ID: 3620430 • Letter: W
Question
Write a multithreaded program that generates the Fibonacci sequence using either the Java,Pthreads, or Win32 thread library. This program should work as follows: 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.
I have code written using fork but having trouble using threads now:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#define MAX_SEQUENCE 10
typedef struct {
long fib_sequence[MAX_SEQUENCE];
int sequence_size;
} shared_data;
int main( int argc,char *argv[] ){
int a=0,b=1,n=a+b,i,ii;
int pid;
int segment_id;
shared_data *shared_memory;
const int size = sizeof(shared_data);
segment_id = shmget ( IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
shared_memory = (shared_data*) shmat (segment_id, NULL, 0);
printf("Please enter a number: ");
scanf(" %d", &ii);
/*Checks to see if a negative value is entered*/
if(ii < 0){
printf("Must be non-negative try again... ");
}else{
pid = fork();
shared_memory-> sequence_size = ii;
shared_memory -> fib_sequence[0]= a;
shared_memory -> fib_sequence[1]= b;
if(pid==0){
printf("%d %d ",a,b);
for(i=2;i<shared_memory -> sequence_size;i++)
{
shared_memory -> fib_sequence[i] = shared_memory -> fib_sequence[i-1] + shared_memory -> fib_sequence[i-2];
printf("Child Fib Sequence: ");
printf("%dl ",shared_memory->fib_sequence[i]);
}
}else{
wait();
int j;
printf("Parent Fib Sequence: ");
for(j=0;j<shared_memory->sequence_size;j++){
printf("%dl ",shared_memory->fib_sequence[j]);
}
shmdt(shared_memory);
shmctl(segment_id,IPC_RMID,NULL);
}
}
return 0;
}
Explanation / Answer
You will have a much easier time using pthreads. #include int shared_data[N]; void * fibonacci_thread(void* arg) { /* compute stuff (set result into shared_data) */ } int main() { pthread_t thread; pthread_create(&thread, NULL, fibonacci_thread, NULL); /* start the thread */ pthread_join(thread, NULL); /* wait for the thread to finish */ /* now you can access shared_data to get the result */ return 0; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.