I am having a trouble exiting a thread using a Restart function. When calling Stop it exits the thread, but Restart which calls Stop and then Start right after - doesn't exit the thread -> calls Start and creates a new thread.
Thanks. Any help would be really helpful and appreciated.
Dummy code to show the problem:
#include <iostream>
#include <thread>
#include <condition_variable>
#include <chrono>
using namespace std;
bool running = false;
unsigned int interval = 5000;
condition_variable cv_work;
mutex mu_cv_work;
void Start()
{
unique_lock<std::mutex> lock(mu_cv_work);
running = true;
lock.unlock();
thread([]{
cout << "new thread" << '\n';
while (running)
{
cout << "work..." << '\n';
unique_lock<std::mutex> lock(mu_cv_work);
cout << "sleep" << '\n';
if (cv_work.wait_for(lock, chrono::milliseconds(interval), []{return running == false;}))
{
cout << "exit thread" << '\n';
return;
}
cout << "done sleeping" << '\n';
}
}).detach();
}
void Stop()
{
unique_lock<std::mutex> lock(mu_cv_work);
running = false;
lock.unlock();
cv_work.notify_one();
}
void Restart()
{
Stop();
Start();
}
int main()
{
Start();
cout << "press to Stop" << '\n';
cin.get();
Stop(); // Stop actually exits the Thread
cout << "press to Start" << '\n';
cin.get();
Start();
cout << "press to Restart" << '\n';
cin.get();
Restart(); // Stop doesn't exit the Thread (Restart calls Stop() and Start())
return 0;
}
Output:
press to Stop
new thread
work...
sleep
// KEY PRESS
exit thread
press to Start
// KEY PRESS
new thread
work...
sleep
press to Restart
// KEY PRESS
new thread
work...
sleep
done sleeping
work...
sleep
Expected output:
press to Stop
new thread
work...
sleep
// KEY PRESS
exit thread
press to Start
// KEY PRESS
new thread
work...
sleep
press to Restart
// KEY PRESS
exit thread // THIS LINE
new thread
work...
sleep
done sleeping
work...
sleep