I'm basically using std::future and std:: promise in a way just opposite to how it was intended to be used(i.e what it seems to me).
It works, but there should be a less kludgy way to do the same thing.
Before yelling "Premature Optimization" note that I'd like to use a similar construct to play around with sorting algorithms.
So, adding the extra check at every iteration may not be good....though the asymptotic complexity won't change (afaik).
(After that feel free to say so )
Code:
#include<iostream>
#include<future>
#include<thread>
#include<chrono>
void foo(std::promise<bool>& p)
{
std::future<bool> f= p.get_future();
long i=1;
while(i++) //This is the loop I want to kill ...
if(f.wait_for(std::chrono::seconds(0))==std::future_status::ready)
break;
std::cout<<"Counted to :"<<i<<std::endl;
return ;
}
int main()
{
std::promise<bool> p;
std::thread t(foo,std::ref(p));
while(true)
{
char c;
std::cout<<"$:";
std::cin>>c;
if(c=='q')
{
p.set_value(true); //...by sending a message or setting a flag from elsewhere/
break;
}
}
t.join();
return 0;
}