【问题标题】:What is the difference between concurrent.futures and asyncio.futures?concurrent.futures 和 asyncio.futures 有什么区别?
【发布时间】:2015-07-06 07:53:59
【问题描述】:

澄清这个问题的原因:

  1. 使用同名的两个模块会造成混淆。它们代表什么使它们与众不同?

  2. 一个人可以解决哪些任务而另一个人不能解决,反之亦然?

【问题讨论】:

  • 对于任何需要在使用 asyncio 的代码中使用 concurrent.futures Future 对象的人,请将 Future 对象与 asyncio.wrap_future 包装起来,这样它们就变成了 awaitable

标签: python python-3.x module python-asyncio concurrent.futures


【解决方案1】:

asyncio documentation 涵盖了差异:

asyncio.Future(*, loop=None)

这个类几乎兼容concurrent.futures.Future

区别:

  • result()exception() 不接受超时参数,并在未来尚未完成时引发异常。
  • 使用add_done_callback() 注册的回调始终通过事件循环的call_soon_threadsafe() 调用。
  • 此类与concurrent.futures 包中的wait()as_completed() 函数不兼容。

这个类不是线程安全的。

基本上,如果您使用ThreadPoolExecutorProcessPoolExecutor,或者想直接将Future 用于基于线程或基于进程的并发,请使用concurrent.futures.Future。如果您使用的是asyncio,请使用asyncio.Future

【讨论】:

  • 所以它不是线程安全的,除非你使用add_done_callback()?
  • asyncio.Future 根本不是线程安全的——它只设计用于基于asyncio 的单线程应用程序。如果要从事件循环线程之外的线程调用asyncio.Future 上的方法,则需要使用loop.call_soon_threadsafe
【解决方案2】:

来自docs

[asyncio 提供了一个] Future 类,它模仿 concurrent.futures 模块中的类,但适用于事件循环;

【讨论】:

  • 这是否意味着它们具有重复的功能?
  • 是的;请参阅asyncio.futures.Future 的文档字符串。
  • 谢谢,我读的文档字符串越多,区别就越明显。
猜你喜欢
  • 2014-09-13
  • 2014-09-17
  • 2010-10-02
  • 2011-12-12
  • 2010-09-16
  • 2012-03-14
  • 2012-02-06
  • 2011-02-25
  • 2011-11-22
相关资源
最近更新 更多