mercredi 14 juillet 2021

C++11 getting std::future data updated from a thread

I have a udp socket running on a separate thread. I need to get certain data only periodically, something like:

void runThread(udpSocketObj s, std::promise<int>* f1, std::promise<int>* f2)
{
    s->rec(ret);
    ...
    f1->set_value(someValue in ret);
    f2->set_value(someOtherValue in ret);
}
int main(int argc, char **argv){
    
    std::promise<int> p1, p2;
    std::future<int> f1 = p1.get_future();
    std::future<int> f2 = p2.get_future();
    mythread = std::thread(runThread, myScoketObj, &p1, &p2);
    mythread.detach();
    int myV1 = f1.get();
    int myV2 = f2.get();

}

f1 and f2 should only be updated periodically. If i have a receiving loop going in runThread, when they are updated the second time, it throws a "promise already satisfied" error. Is it possible to keep mySocket in a receiving loop but get the future data updated only when needed?

Aucun commentaire:

Enregistrer un commentaire