You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

空while循环子线程导致主线程psutil.net_connections()执行极慢的原因咨询

空while循环子线程导致主线程psutil.net_connections()执行极慢的原因咨询

我遇到了一个很费解的问题:当我在代码里启动一个包含空while循环的子线程后,主线程调用psutil.net_connections()的速度变得异常缓慢,往往要等待约一分钟才能得到结果。我的代码如下:

import psutil
import time
import threading
import os  # 补充原代码遗漏的导入

pid = os.getpid()
proc = psutil.Process(pid)

exit = False

def MyThread1():
    while True:
        if exit == True:
            break
        # time.sleep(1)

t1 = threading.Thread(target=MyThread1, args=[])
t1.start()

connections = psutil.net_connections()

for con in connections:
    print(con.laddr.port)

exit = True
t1.join()

当我在代码运行过程中按下Ctrl+C中断时,发现中断发生在lock.acquire()操作期间,当时正在执行readlink函数:

File "/home/mz/pyenv/lib/python3.11/site-packages/psutil/_pslinux.py", line 215, in readlink
    path = os.readlink(path)
           ^^^^^^^^^^^^^^^^^
KeyboardInterrupt
^CException ignored in: <module 'threading' from '/usr/lib/python3.11/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.11/threading.py", line 1590, in _shutdown
    lock.acquire()
KeyboardInterrupt: 

更奇怪的是,只要我在空while循环中添加time.sleep(1)这一行代码,整个程序就会运行得完全正常。我查阅了Python线程相关的文档,但没找到关于调度器工作机制的详细说明。之前了解到Python大概每执行100字节码就会进行任务上下文切换,但我还是搞不懂为什么会出现这种现象。我使用的是Python 3.11.9版本,有没有大佬能帮我解释下这个问题呀?

备注:内容来源于stack exchange,提问作者mztulip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:50:31