Python线程什么时候快速? [英] When are Python threads fast?

查看:82
本文介绍了Python线程什么时候快速?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道 GIL 的恐怖之处,关于使用multiprocessing模块的正确时间的大量讨论,但是我仍然不认为我对使用Python线程(主要关注CPython)何时是正确的答案有很好的直觉.

We're all aware of the horrors of the GIL, and I've seen a lot of discussion about the right time to use the multiprocessing module, but I still don't feel that I have a good intuition about when threading in Python (focusing mainly on CPython) is the right answer.

在哪些情况下,GIL并非重大瓶颈?线程是最合适答案的用例类型是什么?

What are instances in which the GIL is not a significant bottleneck? What are the types of use cases where threading is the most appropriate answer?

推荐答案

只有在发生大量阻塞I/O时,线程才有意义.如果真是这样,那么某些线程可以睡眠,而其他线程可以工作.如果线程受CPU限制,那么多线程不太可能带来很多好处.

Threading really only makes sense if you have a lot of blocking I/O going on. If that's the case, then some threads can sleep while other threads work. If threads are CPU-bound, you're not likely to see much benefit from multithreading.

请注意,虽然 multiprocessing 模块虽然更难编写代码,但却使用了单独的流程,因此不会使用不会遭受GIL的不利影响.

Note that the multiprocessing module, while more difficult to code for, makes use of separate processes and therefore doesn't suffer the downsides of the GIL.

这篇关于Python线程什么时候快速?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆