2

我有以下 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循环中稍微休眠一下,导入会更快。

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无限while循环中没有睡眠语句需要这么长时间。

4

2 回答 2

3

CPython 使用全局解释器锁来保护解释器上下文。这可以防止线程同时运行。实际上它们都在单个处理器内核上运行。在 CPython 中,当线程执行类似空闲的操作(即等待 IO 或侦听套接字)时,您可以从线程中受益。
你为主线程做了很多工作。虽然pass没有做任何有趣的事情,但它会消耗 CPU 周期,而且解释器认为为该线程提供 CPU 时间很重要。
sleep你说don't waste anything for this thread until time expires

于 2014-03-25T07:58:00.923 回答
0

我不是该主题的专家,但据我所知,多个线程一个接一个地在同一个内核上运行,所以这是 CPU 时间共享的问题。然后将睡眠添加到无限循环将为您的导入线程提供更多资源。要并行运行,请使用多处理。那么您的代码将使用多个核心。你可以看看这个简单的例子

于 2014-03-25T07:57:10.910 回答