I create a non-detached thread which can be stopped through 2 different methods. One of them (stop()
) provides a sync interface by joining to the spawned thread while the other one (stopAsync()
) just sets the control variable m_continue
to false and doesn't wait for the mentioned thread to finish.
void run()
{
while(m_continue)
{
// Do something
}
}
void start()
{
m_continue = true;
// Spawn a new thread for run()
}
void stop()
{
m_continue = false;
// Join to the spawned thread
}
void stopAsync()
{
m_continue = false;
}
In case of stopAsync()
is called, the while loop in the run()
method finishes but no one joins to that thread. Is there any resource leak for this case ? Is it compulsory to join a non-detached thread ?
I couldn't figure out from the documentation. The 'Notes' part tells something that I am not able to understand.
A thread may either be joinable or detached. If a thread is joinable, then another thread can call pthread_join(3) to wait for the thread to terminate and fetch its exit status. Only when a terminated joinable thread has been joined are the last of its resources released back to the system. When a detached thread terminates, its resources are automatically released back to the system: it is not possible to join with the thread in order to obtain its exit status. Making a thread detached is useful for some types of daemon threads whose exit status the application does not need to care about. By default, a new thread is created in a joinable state, unless attr was set to create the thread in a detached state (using pthread_attr_setdetachstate(3)).