python中的多线程是神话吗? [英] Is multithreading in python a myth?

查看:104
本文介绍了python中的多线程是神话吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,系统中可以同时产生多个线程,但是2个不同的线程不能同时访问或修改同一资源.我什至尝试了很多事情,例如创建多个线程并将它们放入队列等.但是我经常听到人们说多线程在Python中不可用,相反,您可以使用多处理来利用多核CPU.

To the best of my knowledge, multiple threads can be spawned within the system concurrently but 2 different threads can not access or modify the same resource at the same time. I have even tried many things like creating many threads and putting them in a queue etc. But always I used to hear people say multithreading is not available in Python and that instead you can use multiprocessing to take advantage of multicore CPUs.

这是真的吗? Python线程仅是绿色线程,不是真正的多线程吗?我对Python的资源锁定是否正确?

I this true? Are Python threads only green threads, not real multithreading? Am I right about the resource locking of Python?

推荐答案

否,Python确实具有多线程.实际上,它使用系统线程.问题在于它不能使用多个可用内核中的一个.这是由于称为> GIL ( Global Interpreter Lock >). Python线程仍然适用于I/O绑定的任务,而不是CPU绑定的任务,这可能会导致死锁和竞争条件.许多Python库通过使用C扩展绕过GIL来解决此问题.当然,在CPython中都是这样.

No, Python does have multithreading. In fact, it uses system threads. The problem is just that it can't use more than one of the available cores. This is due to something called the GIL(Global Interpreter Lock). Python threads still work for I/O bound tasks as opposed to CPU bound tasks which may cause deadlocks and race conditions. Many Python libraries solve this issue by using C extensions to bypass the GIL. Of course, this is all in the case of CPython.

Python的一位核心开发人员对此进行了非常有趣的讨论.

There is a very interesting talk about this by one of the core developers of Python.

关于并发性的Raymond Hettinger

现在您是对的,使用多处理以获得所有内核的好处要好得多.但是内核比线程少得多.内核是宝贵的资源,并占用大量内存.如果您不介意处理 IPC(进程间通信),那么它就是一个很好的解决方案.

Now you are right, it is much better to use multiprocessing to get the benefit of all the cores. But there are much fewer cores than there are threads. Cores are valuable resources and take up a lot of memory. If you don't mind dealing with IPC(Interprocess Communication), then it is a great solution.

这篇关于python中的多线程是神话吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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