0
votes

I have 16 threads that spawned from one parent thread. I'm waiting for the children to finish execution by calling pthread_join in the parent. However, afterwards in each of the children threads I call pthread_detach. I'm wondering if the parent will still wait for the children to finish executing. In the man page it says for pthread_detach: "When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread."

1

1 Answers

4
votes

Can I call pthread_join on a pthread_detached thread?

No.

I'm wondering if the parent will still wait for the children to finish executing.

It's undefined behaviour.

pthread_join says:

The behavior is undefined if the value specified by the thread argument to pthread_join() does not refer to a joinable thread.

A detached thread is not joinable.

If a child thread changes itself to detached while another thread is trying to join it, you are now joining a non-joinable thread.

You should call either pthread_join or pthread_detach at most once for each thread. Do not call both for the same thread.