Python多久切换一次线程? [英] How often does Python switch threads?

查看:270
本文介绍了Python多久切换一次线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在cPython(默认的Python实现)中,线程切换多久进行一次?这不是关于使用多个内核的问题.我了解GIL,并意识到一次只能运行一个线程.

In cPython (the default Python implementation), how often does thread switching happen? This is not a question about using multiple cores; I know about the GIL, and realize that only one thread will be run at at time.

我见过一些情况,其中我依次有两个日志消息,并且将发出第一条日志消息,但是第二秒钟不会发出第二条日志消息.这可能是因为Python决定在两个日志语句之间切换线程.这使我相信Python每隔几秒钟就会在线程之间切换一次,这比我预期的要慢得多.这是正确的吗?

I have seen a few cases where I have two log messages in sequence, and the first log message will be emitted, but the second is not emitted for several seconds. This probably happens because Python decided to switch threads in between the two log statements. This leads me to believe that Python switches between threads once every couple of seconds, which is much slower than I would have expected. Is this correct?

推荐答案

默认情况下,Python 2将每100条指令切换一次线程.可以使用sys.setcheckinterval对此进行调整,该文档在此处记录: https://docs.python.org/2/library/sys.html#sys.setcheckinterval

By default, Python 2 will switch threads every 100 instructions. This can be adjusted with sys.setcheckinterval which is documented here: https://docs.python.org/2/library/sys.html#sys.setcheckinterval

我在此演示文稿的第10、11和12页上找到了更多信息: http://www.dabeaz.com/python/UnderstandingGIL.pdf

I found additional information on pages 10, 11, and 12 of this presentation: http://www.dabeaz.com/python/UnderstandingGIL.pdf

(这些答案来自问题的评论,但由于没有人将其写下来,所以我会自己做.评论发表以来已经有6个多月了.)

(These answers come from the comments of the question, but since nobody has written them down in an answer I will do it myself. It has been 6+ months since the comments were made.)

更新:

自Python 3.2起,不推荐使用sys.setcheckinterval. CPython有另一种改进GIL的方法.他们没有在100条虚拟指令后释放GIL,而是改为按时间间隔切换.

Since Python 3.2, sys.setcheckinterval was deprecated. CPython has another approach to improve the GIL. Instead of release the GIL after 100 virtual instruction, they changed to switch by time interval instead.

默认情况下,GIL将在5毫秒(5000微秒)后释放,以便其他线程可以进行更改以获取GIL.您可以使用 sys.setswitchinterval 更改此默认值.

By default, the GIL will be released after 5 milliseconds (5000 microseconds) so that other thread can have a change to acquire the GIL. And you can change this default value by using sys.setswitchinterval

这篇关于Python多久切换一次线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆