Removing the daemon stream only after it returns

I am working on a project in which I have a main thread and one daemon thread to execute output files. In my main thread, I have a field pthread_t * _daemonthat I would like to delete, but, obviously, only after it _daemonreturns NULL (I understand that using pthread_exit()causes a memory leak).

How can I do this without employment? If I try to use a condition variable, I have a problem. When I call signal()form _daemonto wake my main thread, it deletes _daemonbefore _daemonreturning NULL.

What I did was just use the mutex lock, which locks when the program starts and unlocks until it returns _daemon. Is there a better way that would not cause a wait?

+5
source share
2 answers

pthread_detach()does what you are looking for. It seems like this will solve your problem (no leak) with much less complexity!

That way, you can safely call pthread_detatch(_daemon)when you are done with it inside another thread, without worrying about the thread itself still working. It does not terminate the thread; instead, it causes the thread to clear when it terminates.

From the documentation:

pthread_detach() , . , pthread_detach() .

, attr :

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

. man- pthread_create() :

, . [snip] , . default, , attr ( pthread_attr_setdetachstate (3)).

+5

pthread_t unsigned long int, pthread_t ( pthread), , pthread ( , - , ..).

+1

All Articles