Python中的线程效率如何? [英] How efficient is threading in Python?

查看:81
本文介绍了Python中的线程效率如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说在Python中线程化不是很有效(与其他语言相比).

I heard threading is not very efficient in Python (compared to other languages).

这是真的吗?如果是这样,Python程序员该如何克服呢?

Is this true? If so, how can a Python programmer overcome this?

推荐答案

人们之所以说多线程在python中不是很有效的原因是因为全局解释器锁.由于解释器的编写方式,因此只有一个线程可以安全地同时在解释器中执行代码.

The reason people say that multi-threading is not very efficient in python is because of the Global Interpreter Lock. Because of the way the interpreter is written, only one thread can safely execute code in the interpreter at the same time.

这意味着,如果您的线程具有很高的计算范围,也就是说,在解释器中做了很多工作,那么您实际上仍然仅具有单线程程序的性能.在这种情况下,您最好使用多处理模块,该模块具有与多线程模块相同的接口,但是会启动解释器的多个副本(这样做的缺点是您必须显式共享内存).

This means that if you have threads which are quite heavily compute bound, that is, doing lots of stuff in the interpreter, then you effectively still only have the performance of a single threaded program. In this case you might be better off using the multiprocessing module, which has the same interface as the multithreading module but launches multiple copies of the interpreter (the downside of this is that you will have to explicitly share memory).

如果您正在做大量受IO约束的事情,您仍然可以从python中的多线程中获得速度收益.当一个线程在等待磁盘或网络I/O时,其他线程仍然可以执行,因为当线程阻塞时,它们会释放解释器锁.

Where you still can reap speed gains from multithreading in python is if you are doing something that is heavily IO bound. While one thread is waiting for disk or network i/o the other threads can still execute, because when threads block they release the interpreter lock.

这篇关于Python中的线程效率如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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