多线程操作系统系统调用不会同时运行



以下代码的运行时间为5秒,而不是预期的1秒:

import threading, os
def wait_one_second(): 
print(f"{threading.current_thread().name}: Hi!")
os.system('sleep 1')
print(f"{threading.current_thread().name}: Bye!")
for _ in range(5):
thread = threading.Thread(target = wait_one_second)
thread.start()

对os.system的调用会阻塞GIL吗?当我用subprocess.call调用替换os.system调用时,问题就解决了,但后者打开了一个新的进程,这有点违背了目的。

你有可能在M1 Mac上运行这个吗?

我在M1 Mac(macOS Big Sur,Python 3.9.5(和Debian 11(Python 3.9.2(上运行了相同的代码;再见"消息都在我的Debian机器上同时打印,它们在我的M1 Mac上连续打印,每次打印之间有1秒的延迟。

最新更新