vendredi 12 mai 2023

what is the way to use class instance (no copy ctor ) for lambda used in condition variable wait_util? [duplicate]

code snippet looks like: //main.cpp:

in main()
{
   Demo demo; //Instance for class Demo

   while(1)
   {
     std::mutex cv_m;
     std::unique_lock<std::mutex> lock(cv_m);
     std::chrono::seconds time_period(20);
     auto time_duration = std::chrono::system_clock::now() + time_period;

     //this is wrong, but just show what I want to do
     if(demo.cond_var.wait_util(lock, timeDuration, [demo, event_num](){return demo.getEventNum() == event_num; })){
       std::cout<<" Reach the points!"<<std::endl;
       break;
     }
    else{
       std::cout<<"Timed out!"<<std::endl;
       break;
    }


   }

}

The purpose is to keep checking the event number (which will be updated by other threads), if it reaches to 20, break from the loop or till it times out.

Above code failed to compile with error: use of deleted function Demo(const Demo&) So my question is if without copy ctor, is there a way to do what I want to do? I may not able to allow to add the copy ctor for the class.

Thanks.

Aucun commentaire:

Enregistrer un commentaire