1. Both use pthread_join(). The output is straightforward. The program won't go on until pthread_join() return.
2. Both use pthread_detach(). The order of sub-thread and main-thread is uncertain. the program won't wait return of fn1 or fn2.
3. Use neither pthread_join() or pthread_detach(). The output seems the same with case 2.
I can understand case 1. However, why the outputs of case 2 and case 3 seem the same? In that case, what is the effect of pthread_detach()?
Maybe the outputs are different(I am not sure) then why are they different?
In (2) and (3) it's possible that "thread 1 returning." and/or "thread 2 exiting." are never printed, if the main thread terminates before those messages are printed.
I think "detach" does not affect how the threads run. It's just that if the thread is detached it will be cleaned up automatically when it terminates. If it's not detached it is not cleaned up completely, so might still use some memory (and possibly other resources?) until you join it.
Hello,I think the subthread begins when you call pthread_create().If you don't call pthread_detach(),the subthread begins,and if you call it,the subthread still begins.The difference between case2 and case3 is that if you call pthread_detach().The subthread's resource will be released automatically when it terminates,and if you don't call it,some resources it has can't be released.