Calling pthread_cancel on a join'ed thread causes segfault under linux

后端 未结 1 1329
無奈伤痛
無奈伤痛 2021-01-13 22:13

The following code ends with a segmentation fault on the first call to pthread_cancel but only under linux. Under Mac OS it runs fine. Am I not allowed to call pthread_cance

相关标签:
1条回答
  • 2021-01-13 23:08

    See POSIX XSH 2.9.2:

    Although implementations may have thread IDs that are unique in a system, applications should only assume that thread IDs are usable and unique within a single process. The effect of calling any of the functions defined in this volume of POSIX.1-2008 and passing as an argument the thread ID of a thread from another process is unspecified. The lifetime of a thread ID ends after the thread terminates if it was created with the detachstate attribute set to PTHREAD_CREATE_DETACHED or if pthread_detach() or pthread_join() has been called for that thread. A conforming implementation is free to reuse a thread ID after its lifetime has ended. If an application attempts to use a thread ID whose lifetime has ended, the behavior is undefined.

    If a thread is detached, its thread ID is invalid for use as an argument in a call to pthread_detach() or pthread_join().

    You may not use a pthread_t after the thread it refers to has been joined, or if the thread has terminated while detached. Simply remove the pthread_cancel code from your program. It's wrong. pthread_cancel is for cancelling an in-progress thread, and has very tricky requirements for using it safely without causing resource leaks. It's not useful for threads which exit on their own.

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