0
Delay
개체를 비동기 적으로 생성 한 다음 (다른 스레드에서) 해당 개체에서 함수 foo
을 반복적으로 호출하려고합니다.std :: future :: get 반복적으로 호출
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;
}
그러나 두 번째로 x.get()이 호출되면 예외가 발생합니다.
이러한 상황을 처리하는 데 권장되는 방법은 무엇입니까? 아래 표시된 플래그를 사용하면 해킹처럼 보입니다. 더 좋은 방법이 있습니까?
bool is_set = false;
std::unique_ptr<Delay> ptr;
void run_ptr() {
if (!is_set) {
ptr = x.get();
is_set = true;
}
ptr->out();
}