Python 3.2及以后的sys.setswitchinterval

18 投票
2 回答
2477 浏览
提问于 2025-04-17 02:01

Python 3.2 引入了一个新的全局解释器锁(GIL)实现,这个改进是由 Antoine Pitrou 提出的。这个新实现让我们可以使用一个叫做 sys.setswitchinterval 的函数。

那么,什么时候改变这个设置会有用呢?为什么呢?

2 个回答

2

这样做更一致,也更容易预测。

之前,解释器每完成N条虚拟指令就会切换线程,而每条指令的完成时间可能会很长,完全不固定。

8

一个用途是确保操作能够原子性地运行,也就是说,这些操作要么全部完成,要么一个都不做,像这样:

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)

另一个用途是在你遇到车队效应(或者其他一些特殊情况,导致新的全局解释器锁性能不佳)时,调整你的代码。也许(只是也许)改变上下文切换的时间间隔可以让你的代码运行得更快。

免责声明:上面提到的第一种方法被认为是黑魔法,完全不推荐使用(在这种情况下,建议使用threading.Lock之类的工具)。一般来说,我认为在正常情况下不应该去改变线程的上下文切换时间间隔。我想引用Tim Peters说过的话:改变线程上下文切换时间间隔的技术是99%的人都不需要的深奥魔法

撰写回答