Python中的线程 [英] Threading in Python

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

问题描述

在Python中用于编写多线程应用程序的模块有哪些?我知道该语言以及无堆栈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?

推荐答案

按复杂度递增的顺序:

优点:

  • 在其中运行任何函数(实际上是任何可调用的)真的很容易 自己的线程.
  • 如果不是那么容易共享数据(锁定永远都不容易:),位于 最简单的.
  • It's really easy to run any function (any callable in fact) in its own thread.
  • Sharing data is if not easy (locks are never easy :), at least simple.

缺点:

  • 如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的示例,然后将threading替换为,带有ProcessThread和带有multiprocessing.QueueQueue(模块),它应该可以正常运行.)

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天全站免登陆