Python 3.2引入了一个由Antoine Pitrou提供的new GIL implementation,该函数公开了函数sys.setswitchinterval
。Python 3.2及更高版本中的sys.setswitchinterval
什么时候改变它会有用,为什么?
Python 3.2引入了一个由Antoine Pitrou提供的new GIL implementation,该函数公开了函数sys.setswitchinterval
。Python 3.2及更高版本中的sys.setswitchinterval
什么时候改变它会有用,为什么?
的用途之一将是确保操作(S)原子运行,例如:
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)
另一种使用情况将是你的代码特别是当你面对的convoy effect(或任何边缘调新的GIL表现不佳的情况)。也许(也许)更改上下文切换时间间隔可以给你更多的速度。
免责声明:选址上面的第一种方法是考虑黑暗魔法,它是完全不推荐(该threading.Lock
-likes是优选的,使用的情况下)。一般情况下,我认为改变线程上下文切换时间间隔在一般情况下是不可行的。我将解释蒂姆·彼得斯已经提到的元类:changing thread context switch interval is deeper magic than 99% of people are going to need
。
当一个应用程序是IO绑定,你会增加_或_减少它吗? –
@Matt:实际上只有IO绑定线程并不会产生问题,因为每次线程执行一个IO绑定指令时它会释放GIL,但是在使用带有CPU线程的IO绑定线程时可以看到问题,如本文所述问题(http://bugs.python.org/issue7946)在这种情况下(再次)可能会减少切换时间间隔可能会导致更好的性能,因为IO绑定线程不会等待更长时间,如果他们不阻止在所有。 – mouad
+1用于引用此方法中的“黑暗魔法” –
No takers ?! 50代表去一次... –