I want to construct an object Delay
asynchronously and then (from another thread) repeatedly call a function foo
from that object.
struct Delay {
Delay(int d) {
sleep(d);
}
void foo() { }
};
struct Test {
Test() {
x = async(std::launch::async,
[&]() {return std::make_unique<Delay>(4);});
}
void run() { x.get()->foo(); }
std::future<std::unique_ptr<Delay>> x;
};
int main() {
auto t = Test();
// do other stuff...
t.run();
t.run(); // throwing an instance of 'std::future_error', "No associated state"
return 0;
}
However, obviously, the second time x.get() gets called, an exception is thrown.
What is the recommended way to deal with such a situation? Using a flag as shown below seems like a hack. Is there a better way?
bool is_set = false;
std::unique_ptr<Delay> ptr;
void run_ptr() {
if (!is_set) {
ptr = x.get();
is_set = true;
}
ptr->out();
}
Aucun commentaire:
Enregistrer un commentaire