我有以下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
当我执行它时,我发现
import 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()
方法的用法,但我想确切地知道为什么在无限import http.server
循环中没有sleep语句的情况下,为什么要花这么长的时间来使用while
。 最佳答案
CPython使用全局解释器锁来保护解释器上下文。这样可以防止线程同时运行。实际上,它们都在单个处理器内核上运行。在CPython中,当线程执行类似空闲的操作(即等待I.O)时,您可以从中受益。或在 socket 上聆听。
您为主线程做了很多工作。尽管pass
没什么有趣的事情,但它消耗了CPU周期,并且解释器认为给该线程分配CPU时间很重要。
使用sleep
时,您说don't waste anything for this thread until time expires
。
关于python - 当主线程运行无限循环时,为什么要花很长时间在不同的线程中导入模块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22628294/