Python 中的线程 [英] Threading in Python

查看:29
本文介绍了Python 中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用 Python 编写多线程应用程序的模块有哪些?我知道该语言和 Stackless Python 提供的基本并发机制,但是它们各自的机制是什么优点和缺点?

What are the modules used to write multi-threaded applications in Python? I'm aware of the basic concurrency mechanisms provided by the language and also of Stackless Python, but what are their respective strengths and weaknesses?

推荐答案

按复杂程度递增:

优点:

  • 在其内部运行任何函数(实际上是任何可调用的)真的很容易自己的线程.
  • 共享数据并不容易(锁定从来都不是一件容易的事:),在最不简单.

缺点:

  • 正如 作者 Juergen 所述,Python 线程实际上无法同时访问解释器中的状态(有一个大锁,臭名昭著的全局解释器锁.)这在实践中意味着线程是对 I/O 绑定任务(网络、写入磁盘等)很有用,但对进行并发计算完全没有用.
  • As mentioned by Juergen Python threads cannot actually concurrently access state in the interpreter (there's one big lock, the infamous Global Interpreter Lock.) What that means in practice is that threads are useful for I/O bound tasks (networking, writing to disk, and so on), but not at all useful for doing concurrent computation.

在简单的用例中,这看起来与使用 threading 完全一样,只是每个任务都在自己的进程中运行,而不是在自己的线程中运行.(几乎从字面上看:如果您采用 Eli 的示例,并替换 threadingmultiprocessingThreadProcessQueue(模块)与 multiprocessing.队列,它应该运行得很好.)

In the simple use case this looks exactly like using threading except each task is run in its own process not its own thread. (Almost literally: If you take Eli's example, and replace threading with multiprocessing, Thread, with Process, and Queue (the module) with multiprocessing.Queue, it should run just fine.)

优点:

  • 所有任务的实际并发(无全局解释器锁).
  • 可扩展到多个处理器,甚至可以扩展到多台机器.

缺点:

  • 进程比线程慢.
  • 进程之间的数据共享比线程更棘手.
  • 内存不是隐式共享的.您要么必须明确共享它,要么必须腌制变量并来回发送它们.这更安全,但更难.(如果这越来越重要,Python 开发人员似乎正在推动人们朝这个方向发展.)

优点:

  • 您可以非常精细地控制优先级和执行时间.

缺点:

  • 即使有一个好的库,异步编程通常也比线程编程更难,在理解应该发生的事情和调试实际发生的事情方面都很困难.

所有情况下,我假设您已经了解多任务处理涉及的许多问题,特别是如何在任务之间共享数据的棘手问题.如果由于某种原因您不知道何时以及如何使用锁和条件,您必须从这些开始.多任务代码充满了微妙之处和陷阱,最好在开始之前对概念有一个很好的理解.

In all cases I'm assuming you already understand many of the issues involved with multitasking, specifically the tricky issue of how to share data between tasks. If for some reason you don't know when and how to use locks and conditions you have to start with those. Multitasking code is full of subtleties and gotchas, and it's really best to have a good understanding of concepts before you start.

这篇关于Python 中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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