Gracefully exit a program containing std::async C++

321 views Asked by At

I have the main thread, which calls a function using std:async.

void fileIO() {
  while (true) {
    SomeClass::someStaticFunction();
  }
}

int main() {
    ...
    ...
    std::future<void> fileIOFuture = async(std::launch::async, fileIO);

    while (!exitMainloop) // this value is set somewhere else in the code: https://github.com/TigerVNC/tigervnc/blob/master/vncviewer/vncviewer.cxx#L702
        run_mainloop();

    delete cc; // cc is some class

    return 0;
}

What I want is that when the exitMainloop value gets set i.e. the main loop exits, the worker thread created by the std::async call should also gracefully exit.

I read this which says you can't cancel/stop a thread in C++. But I believe this must be a fairly common use case. So, in general how are such situations handled. How do I gracefully terminate the program?

0

There are 0 answers