为什么 Python 切换线程?

Why does Python switch threads?

在关于线程和 GIL 的 Python documentation 中,它说:

In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see sys.setswitchinterval())

为什么要这样做?这些上下文切换似乎除了浪费时间之外什么都不做。 运行 每个进程直到它释放 GIL,然后 运行 下一个进程会不会更快?

线程不一定有任何 I/O。您可以让一个线程执行数字 c运行ching,另一个线程处理 I/O。 number-c运行ching thread with your proposal 永远不会丢弃 GIL,因此另一个线程可以处理 I/O。

为了确保每个线程都到达 运行,默认情况下,线程将在 5 毫秒 (Python 3) 后删除 GIL 如果之前没有这样做,因为等待 I/O.

您可以使用 sys.setswitchinterval() 更改此间隔。

线程是一种简单的并发技术。要获得更高效的并发技术,请查看 asyncio,它使用协程提供单线程并发。