0
votes

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)).

https://linux.die.net/man/3/pthread_create

1

1 Answers

0
votes

Only when a terminated joinable thread has been joined are the last of its resources released back to the system.

The implication of this part of the documentation is that some resources for the thread will remain allocated after it has exited, if you don't join it. So doing this is analogous to calling malloc() without free() - it's not "mandatory" in the sense that it won't cause an immediate problem for your program if you don't, but it does represent a resource leak so if you do this repetitively in a long-running program you can exhaust the relevant resource.

In lieu of joining the thread, your stopAsync() can just call pthread_detach() on the other thread before setting the flag variable.

Note that your m_continue variable should be protected by a synchronisation primitive like a mutex or reader-writer lock.