pthread_detach question

后端 未结 5 1905
鱼传尺愫
鱼传尺愫 2020-12-13 05:12

Till recently, I was under the impression that if you \"detach\" a thread after spawning it, the thread lives even after the \"main\" thread terminates.

But a litt

相关标签:
5条回答
  • 2020-12-13 05:34

    To quote the Linux Programmer's Manual:

    The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).

    Also from the Linux Programmer's Manual:

    To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

    0 讨论(0)
  • 2020-12-13 05:47

    Yes, the detached threads will die after return 0.

    From the NOTES section of man pthread_detach

    The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equiv‐alently, if the main thread returns)

    0 讨论(0)
  • 2020-12-13 05:49

    pthread_detach just means that you are never going to join with the thread again. This allows the pthread library to know whether it can immediately dispose of the thread resources once the thread exits (the detached case) or whether it must keep them around because you may later call pthread_join on the thread.

    Once main returns (or exits) the OS will reap all your threads and destroy your process.

    0 讨论(0)
  • 2020-12-13 05:57

    From man pthread_detach:

    The pthread_detach() function marks the thread identified by thread as detached. 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.

    0 讨论(0)
  • 2020-12-13 05:59

    pthread_detach does not do what you think it does - it indicates to the implementation that the space the thread with the specified ID is using can be reclaimed as soon as it terminates, ie. no pthread_join operation will be performed on it.

    All threads are terminated once the process containing them is terminated.

    0 讨论(0)
提交回复
热议问题