简体   繁体   English

Python多线程,它如何使用多个核心?

[英]Python multithreading, How is it using multiple Cores?

I am running a multithreaded application(Python2.7.3) in a Intel(R) Core(TM)2 Duo CPU E7500 @ 2.93GHz. 我在Intel(R)Core(TM)2 Duo CPU E7500 @ 2.93GHz上运行多线程应用程序(Python2.7.3)。 I thought it would be using only one core but using the "top" command I see that the python processes are constantly changing the core no. 我认为它只使用一个核心但使用“top”命令我看到python进程不断改变核心没有。 Enabling "SHOW THREADS" in the top command shows diffrent thread processes working on different cores. 在top命令中启用“SHOW THREADS”可以显示在不同内核上运行的不同线程进程。

Can anyone please explain this? 有人可以解释一下吗? It is bothering me as I know from theory that multithreading is executed on a single core. 正如我从理论上所知,多线程在单个核心上执行,这让我很烦。

First off, multithreading means the inverse , namely that multiple cores are being utilized (via threading) at the same time. 首先,多线程意味着相反 ,即同时使用多个内核(通过线程)。 CPython is indeed crippled when it comes to this, though whenever you call into C code (this includes parts of the standard library, but also extension modules like Numpy) the lock which prevents concurrent execution of Python code may be unlocked. CPython确实在这方面受到了挫折,尽管每当你调用C代码(这包括部分标准库,还有像Numpy这样的扩展模块)时,可以解锁阻止Python代码并发执行的锁。 You can still have multiple threads, they just won't be interpreting Python at the same time (instead, they'll take turns quite frequently). 你仍然可以有多个线程,他们不会同时解释Python(相反,他们会经常轮流)。 You also speak of "Python processes " -- are you confusing terminology, or is this "multithreaded" Python application in fact multiprocessing ? 您还谈到“Python 进程 ” - 您是否混淆了术语,或者这个“多线程”Python应用程序实际上是多处理 Of course multiple Python processes can run concurrently. 当然,多个Python进程可以并发运行。

However, from your wording I suspect another source of confusion. 但是,从你的措辞中我怀疑是另一个混​​乱的根源。 Even a single thread can run on multiple cores... just not at the same time. 即使是单个线程也可以在多个核心上运行......但不能同时运行。 It is up to the operating system which thread is running on which CPU, and the OS scheduler does not necessarily re-assign a thread to the same CPU where it used to run before it was suspended (it's beneficial, as David Schwartz notes in the comments, but not vital). 由操作系统决定哪个线程在哪个CPU上运行,并且OS调度程序不一定将线程重新分配给它在它被暂停之前运行的同一个CPU(这是有益的,正如David Schwartz在评论,但不重要)。 That is, it's perfectly normal for a single thread/process to jump from CPU to CPU. 也就是说,单个线程/进程从CPU跳转到CPU是完全正常的。

Threads are designed to take advantage of multiple cores when they are available. 线程设计为在可用时利用多个核心。 If you only have one core, they'll run on one core too. 如果你只有一个核心,它们也会在一个核心上运行。 :-) :-)

There's nothing to be concerned about, what you observe is "working as intended". 没有什么值得关注的,你观察到的是“按预期工作”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM