Deleting a daemon thread only after it returns

c++, locking, pthreads

Solution

`pthread_detach()` does what you're looking for. It sounds like it will solve your problem (no leaking) with a lot less complexity!

So you can safely call `pthread_detatch(_daemon)` when you're done with it inside the other thread, without having to worry about if the thread itself is still running. It does not terminate the thread, instead it causes the thread to be cleaned up when it does terminate.

From the documentation:

The `pthread_detach()` function shall indicate to the implementation that storage for the thread thread can be reclaimed when that thread terminates. If thread has not terminated, `pthread_detach()` shall not cause it to terminate.

You can actually create a thread in the detached state to start with by setting `attr` of:

   int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);

appropriately at creation time. The `pthread_create()` manpage says:

When a detached thread terminates, its resources are automatically released back to the system. [snip] 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)).

Problem

I'm working on a project in which I have a main thread and one daemon thread to perform file outputs. In my main thread I have a field `pthread_t * _daemon` that I would like to delete, but obviously only after `_daemon` returns NULL (I understand that using `pthread_exit()` cause memory leaks). How can I do it without busy-wait? If I try to use a condition variable I have a problem - When I call `signal()` form `_daemon` to wake up my main thread, it deletes `_daemon` before it `_daemon` returns NULL. What I did is to just use a mutex lock that is locked when the program is launched and unlocked before `_daemon` returns. Is there any better way that would not cause busy wait?

Original source