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

发布于 2024-12-04 03:36:34 字数 305 浏览 3 评论 0 原文

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

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

Python 3.2 introduced a new GIL implementation by Antoine Pitrou which exposes the function sys.setswitchinterval.

When would changing this be useful, and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傾城如夢未必闌珊 2024-12-11 03:36:34

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

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 的方法是首选)。一般来说,我不认为在正常情况下改变线程上下文切换间隔是应该做的事情。我将解释 Tim Peters 已经说过的关于元类的话:更改线程上下文切换间隔比 99% 的人需要的更深的魔力

One use will be to make sure that operation(s) run atomically, for example:

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)

Another use case will be to tune your code specially when you're facing the convoy effect (or any edge case where the new GIL give bad performance). Maybe (just maybe) changing the context switch interval can give you more speed.

Disclaimer: The first method cited above is considered dark magic and it's totally not recommended (the threading.Lock-likes are preferred in that use case). In general I don't think that changing the thread context switch interval is something to do under normal circumstances. I will paraphrase what Tim Peters already say about metaclasses: changing thread context switch interval is deeper magic than 99% of people are going to need.

半世蒼涼 2024-12-11 03:36:34

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

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

It's more consistent and predictable this way.

Before, the interpreter switched threads every time it completed N virtual instructions, where every instruction could take arbitrary long to complete.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文