Using async launch a thread in main in which the endless loop is spinning. How to complete this thread?
|
2 answers
* .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! - oneCan 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 withstd::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
- oneAnd 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
|
std::mutex, and scroll the loop on the flag. And outside after changing the flag, dostd::join- vegorov