15

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

什么时候改变它是有用的,为什么?

4

2 回答 2

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)

另一个用例是在面临护航效应(或新 GIL 性能不佳的任何边缘情况)时专门调整代码。也许(只是也许)改变上下文切换间隔可以给你更快的速度。

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

于 2011-09-11T10:31:22.547 回答
0

这种方式更加一致和可预测。

以前,解释器每次完成 N 条虚拟指令时都会切换线程,其中每条指令都可能需要任意长时间才能完成。

于 2022-02-17T09:03:35.373 回答