Now, the code takes 866678 clock ticks when the code is run in multithread and when I comment the for loops in the threads(each FOR loop runs 10000 times) and just run the whole FOR loop (20000 times). The run time is same for both with and without threads. But ideally it should have been half right?
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <time.h>
#include<cmath>
#include<unistd.h>
int K = 20000;
long int a[20000];
void makeArray(){
for(int i=0;i<K;i++){
a[i] = i;
}
}
void foo()
{
// do stuff...
std::cout << "FOOOO Running...\n";
for(int i=K/2;i<K;i++){
// a[i] = a[i]*a[i]*10;
// a[i] = exp(2/5);
int j = i*i;
usleep(2000);
}
}
void bar(int x)
{
// do stuff...
std::cout << "BARRRR Running...\n";
for(int i=0;i<K/2;i++){
//a[i] = a[i]*a[i];
int j = i*i;
usleep(2000);
}
}
void show(){
std::cout<<"The array is:"<<"\n";
for(int i=0; i <K;i++){
std::cout<<a[i]<<"\n";
}
}
int main()
{
clock_t t1,t2;
t1 = clock();
makeArray();
// show();
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
//show();
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
//show();
// for(int i=0;i<K;i++){
// int j = i*i;
// //a[i] = a[i]*a[i];
// usleep(2000);
// }
std::cout << "foo and bar completed.\n";
//show();
t2 = clock();
std::cout<<"Runtime:"<< (float)t2-(float)t1<<"\n";
return 0;
}