0

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?

coda
  • 2,188
  • 2
  • 22
  • 26
  • Since your `fileIO` function operates in a loop, it would be simplest that it checks `exitMainloop` as well. But be sure that `exitMainloop` is a `std::atomic` so that you do not introduce a data race. – j6t Dec 13 '20 at 19:52
  • Sooo `while (true) {` -> `while (!exitMainloop) {`? – KamilCuk Dec 13 '20 at 19:52
  • You are right that terminating a thread is a common requirement. Still, C++ does not provide a way to do that when the thread does not cooperate. – j6t Dec 13 '20 at 19:54
  • `std::thread` is probably more appropriate than `std::async` here – Alan Birtles Dec 13 '20 at 20:14

0 Answers0