python线程什么时候切换_Python多久切换一次线程?

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.

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?

解决方案

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

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

(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.)

UPDATE:

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值