I'd like to have an object in C++ that does an asynchronous task in the background, but can still be requested to be freed by code using it without breaking things.
Let's say I have an object like this:
class MyObj {
  std::thread* asyncTask;
  bool result;
  public:
    MyObj() {
      asyncTask = new std::thread([this](){
        result = doSomething();
      });
    };
    bool isResult() {
      return result;
    };
}
How would you go about making sure that the object can still be freed without terminating the process(due to thread still joinable/running at time of destruction)? I've thought about something involving delaying the destructor with a thread running counter, but that doesn't seem like the right solution. Part of the complexity is that the thread needs to normally access elements of the class, so it can't just detach either.
Aucun commentaire:
Enregistrer un commentaire