【问题标题】:sys.setswitchinterval in Python 3.2 and beyondPython 3.2 及更高版本中的 sys.setswitchinterval
【发布时间】:2011-11-14 15:52:45
【问题描述】:

Python 3.2 引入了 Antoine Pitrou 的 new GIL implementation,它公开了函数 sys.setswitchinterval。

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

【问题讨论】:

  • 没有人接受?! 50 次代表一次...

标签: python multithreading python-3.x scheduling gil


【解决方案1】:

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

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)。一般来说,我不认为改变线程上下文切换间隔是正常情况下要做的事情。我将解释一下 Tim Peters 已经说过的关于元类的内容:changing thread context switch interval is deeper magic than 99% of people are going to need。

【讨论】:

  • 当一个应用被IO绑定时,你会增加还是减少它?
  • @Matt:实际上只有 IO 绑定线程不会产生问题,因为每次线程执行 IO 绑定指令时它都会释放 GIL ,但是在使用 IO 绑定线程时可以看到问题使用 CPU 线程,如本期 (bugs.python.org/issue7946) 中所述,在这种情况下(再次)可能减少切换间隔可以带来更好的性能,因为如果 IO 绑定线程没有阻塞,它们将不必等待更长时间全部。
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2015-05-10
  • 2016-03-28
相关资源
最近更新 更多