admin管理员组文章数量:1389762
The python documentation says of daemon threads:
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.
Consider the following example:
import threading
threading.Thread(target=input, daemon=True).start()
Given the above definition, it may be reasonable to assume that executing the above script would cause the process to terminate immediately, as the main thread ends and leaves only the daemon thread in a call to input()
.
However, this example hangs indefinitely waiting for input (tested on CPython 3.10.12 and 3.13.1, intel x86 and Arch Linux).
Attempting to redirect stdout (i.e. python3 test.py > /dev/null
) does not continue to wait for input, but exits after 1-2 seconds with IOT instruction (core dumped)
and the following message to stderr:
Fatal Python error: _enter_buffered_busy: could not acquire lock for <_io.BufferedReader name='<stdin>'> at interpreter shutdown, possibly due to daemon threads
Python runtime state: finalizing (tstate=0x000060b51e205c10)
Current thread 0x00007ad136221080 (most recent call first):
<no Python frame>
In an attempt to locate the cause of this, I tried with the (sufficiently) functionally equivalent sys.stdin.readline()
:
import threading
import sys
threading.Thread(target=sys.stdin.readline, daemon=True).start()
This works as one would expect, and exits immediately, and with no error when redirecting stdout.
I then tried on an ARM machine running Ubuntu and CPython 3.10.12. Both input
and sys.stdin.readline
exit as expected, but the crash when redirecting stdout occurs only for input
.
With CPython 2.7.18, raw_input
and sys.stdin.readline
both cause the indefinite hang without the crash when redirecting stdout on the original machine, and both behave exactly as expected on the ARM machine.
What's going on here? I think there are 4 main questions here:
- Why am I experiencing such different behaviour between
input()
andsys.stdin.readline()
? - Why am I experiencing such different behaviour between python versions?
- Why am I experiencing such different behaviour between machines?
- Why does redirecting stdout trigger a crash?
本文标签: linuxUnpredictable behaviour when reading from stdin in python daemon threadStack Overflow
版权声明:本文标题:linux - Unpredictable behaviour when reading from stdin in python daemon thread - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744683764a2619572.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论