简体   繁体   English

关于Python和C中的多线程的困惑

[英]Confusion about multithreading in Python and C

AFAIK, Python, using import thread , (or C#) doesn't do "real" multithreading, meaning all threads run on 1 CPU core. AFAIK,Python使用import thread (或C#)不会执行“真正的”多线程,这意味着所有线程都在1个CPU内核上运行。

But in C, using pthreads in linux, You get real multithreading. 但是在C语言中,在Linux中使用pthreads,您将获得真正的多线程。

Is this true ? 这是真的 ?

Assuming it is true, is there any difference between them when you have only 1 CPU core (I have it in a VM)? 假设是真的,当您只有1个CPU内核(我在VM中拥有它)时,它们之间有什么区别吗?

I'm not aware of how it works C# internally, but for CPython (the "official" python interpreter) it is true: threads are not really parallel due to GIL . 我不知道它是如何工作的C#内部,但CPython的(“官方” Python解释器),这是真的:线程是不是真的由于平行GIL Other implementation of the Python interpreter do not suffer of this problem (like C's pthreads library). Python解释器的其他实现不会遇到此问题(例如C的pthreads库)。 Howevere if you only have 1 CPU you won't notice any difference. 但是,如果您只有1个CPU,则不会有任何区别。 As a side note: if you need real parallelism in CPython you could you multiprocessing module, which uses processes instead of threads. 附带说明:如果您需要在CPython中真正的并行性,则可以使用进程而不是线程的multiprocessing模块。

EDIT: 编辑:

Also thread module is a bit deprecated, you should consider using threading . 另外thread模块已经过时了,您应该考虑使用threading

Python uses something called a Global Interpreter Lock which means multiple python threads can only run within one native Thread. Python使用一种称为“全局解释器锁”的方法,这意味着多个python线程只能在一个本机线程中运行。

There is more documentation in the official Docs here: https://wiki.python.org/moin/GlobalInterpreterLock 官方文档中有更多文档: https : //wiki.python.org/moin/GlobalInterpreterLock

There shouldn't be a real performance difference on single core systems. 单核系统上不应有真正的性能差异。 On multicore systems the difference will varie based on what you do. 在多核系统上,差异将根据您的工作而有所不同。 (I/O is for the most part not affected by the GIL). (I / O大部分不受GIL的影响)。

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

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