python - 当主线程运行无限循环时,为什么在不同线程中导入模块需要很长时间?

标签 python multithreading python-3.4

我有以下Python代码:

import threading
from datetime import datetime
import time

def f():
    print('---- {:%H:%M:%S}'.format(datetime.now()))
    import http.server
    print('---- {:%H:%M:%S}'.format(datetime.now()))

threading.Thread(target=f).start()

while True:
    pass

当我执行它时,我发现导入http.server消耗了大量时间。正如您从以下输出中看到的,导入花费了 23 秒。

C:\>python foo.py
---- 10:12:03
---- 10:12:26

但是,如果我在无限 while 循环中加入一点 sleep ,导入速度会更快。

import threading
from datetime import datetime
import time

def f():
    print('---- {:%H:%M:%S}'.format(datetime.now()))
    import http.server
    print('---- {:%H:%M:%S}'.format(datetime.now()))

threading.Thread(target=f).start()

while True:
    time.sleep(1)

输出:

C:\>python foo.py
---- 10:15:58
---- 10:15:58

我知道 join() 方法的用法,但我想确切地知道为什么在无限 while 时需要这么长时间import http.server 循环中没有 sleep 语句。

最佳答案

CPython 使用全局解释器锁来保护解释器上下文。这可以防止线程同时运行。实际上它们都在单处理器核心上运行。在 CPython 中,当线程执行类似于空闲的操作(即等待 I.O)时,您可以从线程中受益。或在套接字上监听。
您为主线程付出了很多工作。虽然 pass 没有做任何有趣的事情,但它会消耗 CPU 周期,而且解释器认为为该线程提供 CPU 时间很重要。
对于sleep,你可以说在时间到期之前不要为此线程浪费任何东西

关于python - 当主线程运行无限循环时,为什么在不同线程中导入模块需要很长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22628294/

相关文章:

python - 通过python创建虚拟主机

python - PyPI 包的安装统计数量?

python - 在 python 中使用 SVM 进行回归置信度

c++ - _beginthreadex 内存不足

java - 如何同步我的端口扫描仪,以便结果按照执行顺序显示?

python - Pygame sprite 无效的 rectstyle 对象

Antlr4 Python3 目标访问者不可用?

python - 字符串和列表的连接

ios - 线程安全和 "Collection was mutated while being enumerated"

python - Python odeint 例程可解联立方程数量的限制