I have this code and it gives me an infinite loop as the state of the future is always NOT ready even though the function inside it is finished. I checked the respond function and it always end but the state is never changed to ready.
/**
this class simulate a driver response to the future
*/
class driver {
bool response;
int time;
public:
driver(bool response, int time) : response(response), time(time) {}
bool respond() {
this_thread::sleep_for(std::chrono::milliseconds(time));
return response;
}
};
int check_response(vector<driver> &ds) {
auto f1 = std::async(std::launch::async, [&]() {
return ds[0].respond();
});
auto f2 = std::async(std::launch::async, [&]() {
return ds[1].respond();
});
auto state1 = f1.wait_for(5ms);
auto state2 = f2.wait_for(5ms);
while (
(state1 != future_status::ready)
&&
(state2 != future_status::ready)
) {
auto state1 = f1.wait_for(5ms);
auto state2 = f2.wait_for(5ms);
// never exits this loop
}
if (state1 == future_status::ready && f1.get()) {
return 0;
}
else if (state2 == future_status::ready && f2.get()) {
return 1;
}
else {
return -1;
}
}
int main() {
vector<driver> ds{
{true,300},
{true,10}
};
cout << check_response(ds);
}
Aucun commentaire:
Enregistrer un commentaire