Python 多线程 是还是不是?

发布于 2024-11-07 15:15:57 字数 139 浏览 5 评论 0原文

我一直在尝试编写一个简单的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦冥 2024-11-14 15:15:57

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 to threading 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.

摘星┃星的人 2024-11-14 15:15:57
  • 您不应该需要使用
    线程。 95% 的代码不需要需要
    线程。
  • 是的,Python 线程是
    完全有效,已实施
    通过操作系统的本机
    线程。
  • 使用标准库
    threading 模块,非常棒。
  • You shouldn't need to use
    threading. 95% of code does not need
    threads.
  • Yes, Python threading is
    perfectly valid, it's implemented
    through the operating system's native
    threads.
  • Use the standard library
    threading module, it's excellent.
被你宠の有点坏 2024-11-14 15:15:57

GIL 应该为您提供有关该主题的一些信息。

GIL should provide you some information on that topic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文