CPP: threading in LINUX showing output
#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <future>
#include <functional>
void bar(std::future<int>& fut){
//get the promised variable
//allocate memory for buffer
int len = fut.get(); //get variable
char * buff; //create buffer
buff = (char*) malloc (len+1); //allocate memory
if(buff==NULL){
//exit if no allocation
exit(1);
}
for(int n=0;n<len;n++){
buff[n]=rand()%26+'a';
}
buff[len]='\0';
std::cout<<"\nvalue: "<<buff<<'\n';
free(buff); //free memory
}
void foo(){
//get integer
//create promise
//engage future
//send future to new thread
std::promise<int> malin; //create promise
std::future<int> fut = malin.get_future(); //engage, make it so!
std::thread th1 (bar, std::ref(fut)); //send future to thread
int i,n;
std::cout<<"How long do you want the string? "<<'\n';
std::cin>>i;
//set value of promised integer
malin.set_value(i); //fulfill promise
th1.join(); //join thread with foo
}
int main(){
//spawn new thread calling foo()
//pause intil thread complete
std::thread t1(foo); //launch thread
t1.join(); //join thread with main
return 0;
}
OUTPUT
#include <thread>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <future>
#include <functional>
void bar(std::future<int>& fut){
//get the promised variable
//allocate memory for buffer
int len = fut.get(); //get variable
char * buff; //create buffer
buff = (char*) malloc (len+1); //allocate memory
if(buff==NULL){
//exit if no allocation
exit(1);
}
for(int n=0;n<len;n++){
buff[n]=rand()%26+'a';
}
buff[len]='\0';
std::cout<<"\nvalue: "<<buff<<'\n';
free(buff); //free memory
}
void foo(){
//get integer
//create promise
//engage future
//send future to new thread
std::promise<int> malin; //create promise
std::future<int> fut = malin.get_future(); //engage, make it so!
std::thread th1 (bar, std::ref(fut)); //send future to thread
int i,n;
std::cout<<"How long do you want the string? "<<'\n';
std::cin>>i;
//set value of promised integer
malin.set_value(i); //fulfill promise
th1.join(); //join thread with foo
}
int main(){
//spawn new thread calling foo()
//pause intil thread complete
std::thread t1(foo); //launch thread
t1.join(); //join thread with main
return 0;
}
OUTPUT
Comments
Post a Comment