pthreads in C - pthread_exit

前端 未结 9 1255
北荒
北荒 2021-02-05 14:03

For some reason I thought that calling pthread_exit(NULL) at the end of a main function would guarantee that all running threads (at least created in the main funct

9条回答
  •  渐次进展
    2021-02-05 14:33

    Per normal pthread semantics, as taught e.g. here, your original idea does seem to be confirmed:

    If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

    However I'm not sure whether that's part of the POSIX threads standard or just a common but not universal "nice to have" add-on tidbit (I do know that some implementations don't respect this constraint -- I just don't know whether those implementations are nevertheless to be considered standard compliant!-). So I'll have to join the prudent chorus recommending the joining of every thread you need to terminate, just to be on the safe side -- or, as Jon Postel put it in the context of TCP/IP implementations:

    Be conservative in what you send; be liberal in what you accept.
    

    a "principle of robustness" that should be used way more broadly than just in TCP/IP;-).

提交回复
热议问题