My understanding is if we call get on future obtained from promise then it will wait till set_value is called and if that is never called program will wait forever but somehow this behavior is not working when I am using promise rvalue reference (it is throwing broken promise future error) though same is working with lvalue reference(wait forever). Any reasoning for this because i believe it should wait forever in case of rvalue reference also ?
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
void calculateValue(std::promise<int> &&p)
//void calculateValue(std::promise<int> &p) //uncomment this it will wait
{
using namespace std::chrono_literals;
std::cout<<"This is start of thread function "<<std::endl;
//Do long operations
std::this_thread::sleep_for(2s);
// p.set_value(8);
std::cout<<"This is end of thread function "<<std::endl;
}
int main() {
std::promise<int> p;
auto fut = p.get_future();
std::thread t(calculateValue,std::move(p));
//uncomment this it will wait
//std::thread t(calculateValue,std::ref(p);
std::cout<<"main function ..."<<std::endl;
std::cout<<"value is "<<fut.get()<<std::endl;
t.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire