[英]Is it a Python bug that the main thread of a process created in a daemon thread is a daemon itself?
當我在守護程序線程中調用os.fork()
時,子進程中的主線程將daemon
屬性設置為True
。 這非常令人困惑,因為程序一直在運行,而唯一的線程是守護進程。 根據文檔,如果所有線程都是守護進程,程序應該退出。
這是一個例子:
import os
import threading
def child():
assert not threading.current_thread().daemon # This shouldn't fail
def parent():
new_pid = os.fork()
if new_pid == 0:
child()
else:
os.waitpid(new_pid, 0)
t = threading.Thread(target=parent)
t.setDaemon(True)
t.start()
t.join()
這是CPython實現中的錯誤嗎?
這樣做的原因行為是系統守護進程僅比主線程其他線程相關的。 在主線程中, current_thread().daemon
的返回值被硬編碼為False
。
請在此處查看相關的源代碼:
https://github.com/python/cpython/blob/2.7/Lib/threading.py#L1097
所以在fork之后,只有一個線程,因此它就是主線程。
這意味着它永遠不會成為守護程序線程。
我不能指出你以外的任何文檔,但它肯定不是一個錯誤 - 如果你的期望得到滿足,反過來會是一個bug。
fork和threads之間的交互是復雜的,正如我所提到的:不要在fork之前混合它們。
這非常令人困惑,因為程序一直在運行,而唯一的線程是守護進程。 根據文檔,如果所有線程都是守護進程,程序應該退出。
您明確等待線程結束。 線程是否是守護進程對t.join()
沒有影響。 除非由於os.waitpid()
導致子進程終止,否則該線程將不會再次結束。
我不確定分叉線程的行為,所以我不能告訴你為什么你會經歷你做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.