In: Computer Science
The Fibonacci sequence is the series of numbers 0, 1, 1, 2, 3, 5, 8,.... Formally, it can be expressed as:
fib0 = 0
fib1 = 1
fibn = fibn-1 + fibn-2
Write a multithreaded C++ program that generates the Fibonacci series using the pthread library. This program should work as follows: The user will enter on the command line the number of Fibonacci numbers that the program will generate. The program will then create a separate thread that will generate the Fibonacci numbers placing the sequence in a data structure that is shared by the threads (a vector is probably the most convenient data structure). Note that the thread function should be iterative when calculating fibonacci (can be recursive, but maybe difficult to implement). 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 lectures pertaining to threads. Note that the vector should only have those many terms as the user wanted.
The name of this program must be fibonacci.cpp
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//iterative with output
DWORD WINAPI fib3(LPVOID param){
double u = 0;
double v = 1;
double t;
int upper = *(int*)param;
for(int i = 2; i <= upper; i++){
cout << v << " ";
t = u + v;
u = v;
v = t;
cout << "testing" << endl;
}
cout << v << " ";
return 0;
}
int main(int argc, char *argv[]){
bool done = true;
int x = argv[0] ;
DWORD ThreadId;
HANDLE ThreadHandle;
while(done){
if(x == -1){
cout << "\nExiting" << endl;
return 0;
}
ThreadHandle = CreateThread(NULL, 0, fib3, &x, 0, &ThreadId);
if(ThreadHandle != NULL){
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
}
}
return 0;
}