Using async launch a thread in main in which the endless loop is spinning. How to complete this thread?

  • 3
    add a phalg exit from an infinite loop. - Fat-Zer
  • one
    Options: 1. add the same flag. Reset from the outside. 2. To do to flow to terminate. 3. End the process via terminate - then everything will end. - nick_n_a
  • 2
    Rather, the author must determine whether he wants to have an infinite loop or to be able to complete it. These are mutually exclusive options. - VTT
  • one
    An infinite loop, in terms of C ++, is an undefined behavior. Therefore, add an exit condition and use it. - ixSci
  • one
    @AndrejLevkovitch Well then yes, get the flag to end the stream, protect access to it with, for example, std::mutex , and scroll the loop on the flag. And outside after changing the flag, do std::join - vegorov

2 answers 2

* .pro file for QtCreator:

 TEMPLATE = app CONFIG += console c++11 CONFIG -= app_bundle CONFIG -= qt LIBS += -lpthread SOURCES += main.cpp 

main.cpp:

 #include <iostream> #include <thread> #include <mutex> #include <chrono> #include <cstdlib> #include <future> using namespace std; bool ExitFlag = false; int someVariable = 0; std::mutex threadMutex; void threadFunc(){ while (true){ std::this_thread::sleep_for(std::chrono::seconds(1)); someVariable = std::rand() % 100; std::cout << "var:" << someVariable << std::endl; bool needExit = false; threadMutex.lock(); needExit = ExitFlag; threadMutex.unlock(); if (needExit){ break; } } } int main() { auto f = std::async(std::launch::async, threadFunc); std::this_thread::sleep_for(std::chrono::seconds(10)); threadMutex.lock(); ExitFlag = true; threadMutex.unlock(); f.get(); cout << "Hello World!" << endl; return 0; } 

Conclusion:

 var:83 var:86 var:77 var:15 var:93 var:35 var:86 var:92 var:49 var:21 Hello World! 
  • one
    Can be improved through atomic, using mutex is more expensive - Semerkin
  • @Semerkin is true, more expensive. - vegorov
  • @Semerkin I do not remember the subtleties of std::memory_order , and do not have sufficient knowledge of working with std::atomic<T> , if you are not too lazy to give an example? - vegorov
  • one
    @AndrejLevkovitch I was also surprised when I first tried to use streams from the standard library. And in Visual Studio, everything worked on its own, but at home it was necessary to add pthread to Linux under gcc - vegorov
  • one
    And in principle, this is about the same as while(!needExit) . - bipll

It is impossible to terminate a released stream from the outside, if there is no exit condition in your stream, this is an error.
For Windows, there is a TerminateThread function https://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx , but its use is dangerous and fraught

  • Your answer does not actually contain a solution. Only recommendations and links. Like a cometary - good, like the answer ... - nick_n_a