Python 3.2及更高版本中的sys.setswitchinterval

Mat*_*ner 13 python multithreading scheduling gil python-3.x

Python 3.2引入了Antoine Pitrou的一个新的GIL实现,它公开了这个函数sys.setswitchinterval.

什么时候改变这个有用,为什么?

mou*_*uad 5

一种用途是确保操作以原子方式运行,例如:

sw_interval = sys.getswitchinterval()
try:
    # Setting the switch interval to a very big number to make sure that their will be no
    # thread context switching while running the operations that came after.  
    sys.setswitchinterval(sys.maxint)
    # Expressions run here will be atomic ....
finally:
    sys.setswitchinterval(sw_interval)
Run Code Online (Sandbox Code Playgroud)

另一个用例是在你面对护航效果时(或者新GIL表现不佳的任何边缘情况)特别调整你的代码.也许(只是可能)改变上下文切换间隔可以给你更多的速度.

免责声明:上面提到的第一种方法是考虑黑暗魔法,并且完全不推荐(threading.Lock在该用例中优先使用-likes).一般来说,我不认为在正常情况下更改线程上下文切换间隔是可行的.我将解释蒂姆彼得斯已经说过的关于元类的内容:changing thread context switch interval is deeper magic than 99% of people are going to need.

  • @Matt:实际上只有IO绑定线程不会产生问题,因为每次线程执行IO绑定指令时都会释放GIL,但是当使用带有CPU线程的IO绑定线程时可以看到问题,如本期所述(http://bugs.python.org/issue7946)在这种情况下(再次)可能减少切换间隔可以带来更好的性能,因为IO绑定线程如果不阻塞,则不必等待更长时间所有. (2认同)