Thanks everyone.
I thought about the following design:
Inside the thread itself, I call m_promise.set_value()
after the task finishes:
std::thread([this]()
{
task();
m_promise.set_value();
});
Then, when I want to stop the thread, I do:
if(m_thread.joinable()) {
if (m_future.valid())
m_future.wait(); // Wait until the thread signals it has finished
m_thread.join();
}
This way, I guarantee that by the time I call join()
, the thread has already completed its task.
Would there be any issue with this implementation?
Also, if I want to make it even safer, I thought about adding:
if(!m_alreadyJoining.exchange(true))
m_thread.join();
to protect against joining twice in case of concurrent interrupts.
any feedback ? or what can be an issue here?