是否应该从 main() 返回或调用 exit() 禁用线程取消?
Should returning from main() or calling exit() disable thread cancellation?
当线程调用pthread_exit()
时,POSIX要求取消状态和类型设置为PTHREAD_CANCEL_DISABLE
和PTHREAD_CANCEL_DEFERRED
(XSH 2.9.5,题词下线程取消清理处理程序)由 libc 实现。
从作为参数传递给 pthread_create()
的函数返回的线程应该像调用 pthread_exit()
一样运行。但是,这对于 main()
线程是不同的,从 main()
返回应该表现得像调用 exit()
.
我找不到任何语言将 exit()
链接到禁用取消,或暗示与 pthread_exit()
相同的效果。
那么,是否应该从 main()
返回或调用 exit()
禁用线程取消?
标准函数不允许具有超出指定范围的效果。 exit
未指定对取消状态或类型有任何影响,因此对任何符合要求的实现都没有影响。您可以通过安装调用 pthread_cancel(pthread_self())
然后调用任何取消点的 atexit
处理程序来观察这一点。但是,请注意以下事项:
If a function registered by a call to atexit() fails to return, the remaining registered functions shall not be called and the rest of the exit() processing shall not be completed. If exit() is called more than once, the behavior is undefined.
因此,如果 atexit
处理程序导致取消操作,exit
将不会完成,但再次调用它是未定义的行为。这样的进程必须完全避免退出,使用 _exit
,或通过信号导致自身异常终止。
当线程调用pthread_exit()
时,POSIX要求取消状态和类型设置为PTHREAD_CANCEL_DISABLE
和PTHREAD_CANCEL_DEFERRED
(XSH 2.9.5,题词下线程取消清理处理程序)由 libc 实现。
从作为参数传递给 pthread_create()
的函数返回的线程应该像调用 pthread_exit()
一样运行。但是,这对于 main()
线程是不同的,从 main()
返回应该表现得像调用 exit()
.
我找不到任何语言将 exit()
链接到禁用取消,或暗示与 pthread_exit()
相同的效果。
那么,是否应该从 main()
返回或调用 exit()
禁用线程取消?
标准函数不允许具有超出指定范围的效果。 exit
未指定对取消状态或类型有任何影响,因此对任何符合要求的实现都没有影响。您可以通过安装调用 pthread_cancel(pthread_self())
然后调用任何取消点的 atexit
处理程序来观察这一点。但是,请注意以下事项:
If a function registered by a call to atexit() fails to return, the remaining registered functions shall not be called and the rest of the exit() processing shall not be completed. If exit() is called more than once, the behavior is undefined.
因此,如果 atexit
处理程序导致取消操作,exit
将不会完成,但再次调用它是未定义的行为。这样的进程必须完全避免退出,使用 _exit
,或通过信号导致自身异常终止。