Python 多线程 是还是不是?
我一直在尝试编写一个简单的Python应用程序来实现工作队列 我发现的每个关于线程的网页都有一些随机的人评论它,你不应该使用 python 线程,因为这个或那个,有人可以帮助我吗? Python 线程是怎么回事,我可以使用它吗?如果是的话哪个库?标准的就够了吗?
I have been trying to write a simple python application to implement a worker queue
every webpage I found about threading has some random guy commenting on it, you shouldn't use python threading because this or that, can someone help me out? what is up with Python threading, can I use it or not? if yes which lib? the standard one is good enough?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Python 的线程对于许多任务来说是完全可行且有用的。由于它们是使用本机操作系统线程实现的,因此它们允许执行阻塞系统调用并同时保持“运行” - 通过在单独的线程中调用阻塞系统调用。这对于必须同时执行多项操作(即 GUI 和其他事件循环)的程序非常有用,甚至可以提高 IO 绑定任务(例如网页抓取)的性能。
但是,由于全局解释器锁,如果您希望将 CPU 密集型代码分布在多个 CPU 内核上,它会阻止 Python 解释器实际上同时运行多个线程。 > 使用线程并以这种方式提高性能,你就不走运了。不过,您可以使用
multiprocessing
模块来完成此操作,该模块提供类似于threading
的接口,并使用进程而不是线程来分配工作。我还应该补充一点,C 扩展不需要受 GIL 绑定,并且许多扩展确实会释放它,因此 C 扩展可以通过使用线程来使用多个内核。
因此,这完全取决于您到底需要做什么。
Python's threads are perfectly viable and useful for many tasks. Since they're implemented with native OS threads, they allow executing blocking system calls and keep "running" simultaneously - by calling the blocking syscall in a separate thread. This is very useful for programs that have to do multiple things at the same time (i.e. GUIs and other event loops) and can even improve performance for IO bound tasks (such as web-scraping).
However, due to the Global Interpreter Lock, which precludes the Python interpreter of actually running more than a single thread simultaneously, if you expect to distribute CPU-intensive code over several CPU cores with threads and improve performance this way, you're out of luck. You can do it with the
multiprocessing
module, however, which provides an interface similar tothreading
and distributes work using processes rather than threads.I should also add that C extensions are not required to be bound by the GIL and many do release it, so C extensions can employ multiple cores by using threads.
So, it all depends on what exactly you need to do.
线程。 95% 的代码不需要需要
线程。
完全有效,已实施
通过操作系统的本机
线程。
threading
模块,非常棒。threading. 95% of code does not need
threads.
perfectly valid, it's implemented
through the operating system's native
threads.
threading
module, it's excellent.GIL 应该为您提供有关该主题的一些信息。
GIL should provide you some information on that topic.