最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

linux - Unpredictable behaviour when reading from stdin in python daemon thread - Stack Overflow

programmeradmin1浏览0评论

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:

  1. Why am I experiencing such different behaviour between input() and sys.stdin.readline()?
  2. Why am I experiencing such different behaviour between python versions?
  3. Why am I experiencing such different behaviour between machines?
  4. Why does redirecting stdout trigger a crash?
发布评论

评论列表(0)

  1. 暂无评论