I launched thread as detach. How to close thread from main function?
void My()
{
// actions
}
void main()
{
std::thread thr7(receive);
thr
Use a shared variable to signal threads when to stop.
You cannot call join or terminate a thread directly from its parent once detach is called unless you use some other methods.
Take a look at the following code (over simple and not very meaninful) which should show a simple way of doing what you are asking:
#include
#include
#include
#include
#include
#include
#include
std::mutex mu;
std::condition_variable cv;
bool finished = false;
void threadFunc()
{
while(!finished)
{
std:: cout << "Thread doing work \n";
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
std::cout << "End of Thread \n";
}
int main()
{
{
std::thread t1(threadFunc);
t1.detach(); // Call `detach` to prevent blocking this thread
} // Need to call `join` or `detach` before `thread` goes out of scope
for (int i = 0; i < 5; ++i){
std::this_thread::sleep_for(std::chrono::milliseconds(20));
std::cout << "Main doing stuff: \n";
}
std::cout << "Terminating the thread\n";
std::unique_lock lock(mu);
finished = true;
cv.notify_all();
std::cout << "End of Main\n";
return 0;
}
You use a shared variable to tell the threads when to terminate its execution.