线程在Python中如何工作,以及特定于Python线程的常见陷阱是什么? [英] How do threads work in Python, and what are common Python-threading specific pitfalls?

查看:62
本文介绍了线程在Python中如何工作,以及特定于Python线程的常见陷阱是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力把头放在Python中线程的工作方式上,很难找到关于它们如何运行的好信息.我可能只是缺少链接之类的东西,但似乎官方文档对该主题的了解不是很全面,而且我也找不到很好的文章.

I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.

据我所知,一次只能运行一个线程,活动线程每10条指令左右切换一次?

From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?

哪里有很好的解释,或者您可以提供一个解释?知道在使用Python线程时遇到的常见问题也将是非常高兴的.

Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.

推荐答案

是的,由于全局解释器锁定(GIL),一次只能运行一个线程.以下是一些有关此方面的见解的链接:

Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:

  • http://www.artima.com/weblogs/viewpost.jsp?thread=214235
  • http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/

在最后一个链接中有一个有趣的报价:

From the last link an interesting quote:

让我解释一下这一切的含义. 线程在同一个虚拟机中运行 机器,因此可以在同一机器上运行 物理机器.流程可以运行 在同一台物理计算机上或在 另一台物理机器.如果你 围绕您的应用程序进行架构 线程,您没有执行任何操作 多台机器.因此,您可以扩展 一个核上有尽可能多的核 机器(这将是很多 随着时间的推移),但要真正覆盖网络 规模,您需要解决 无论如何还是多机问题.

Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway.

如果您想使用多核, pyprocessing 定义了一个基于API做真正的并行化. PEP 还包括一些有趣的基准.

If you want to use multi core, pyprocessing defines an process based API to do real parallelization. The PEP also includes some interesting benchmarks.

这篇关于线程在Python中如何工作,以及特定于Python线程的常见陷阱是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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