If the child thread is really exiting when it is done (rather than waiting for more work), the parent thread can call pthread_join
on it which will block until the child thread exits.
Obviously, if the parent thread is doing other things, it can't constantly be blocking on pthread_join
, so you need a way to send a message to the main thread to tell it to call pthread_join
. There are a number of IPC mechanisms that you could use for this, but in your particular case (a TCP server), I suspect the main thread is probably a select
loop, right? If that's the case, I would recommend using pipe
to create a logical pipe, and have the read descriptor for the pipe be one of the descriptors that the main thread selects from.
When a child thread is done, it would then write some sort of message to the pipe saying "I'm Done!" and then the server would know to call pthread_join
on that thread and then do whatever else it needs to do when a connection finishes.
Note that you don't have to call pthread_join
on a finished child thread, unless you need its return value. However, it is generally a good idea to do so if the child thread has any access to shared resources, since when pthread_join
returns without error, it assures you that the child thread is really gone and not in some intermediate state between having sent the "I'm Done!" message and actually having exited.