前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python里使用Future对象来异步

python里使用Future对象来异步

作者头像
py3study
发布2020-01-06 11:29:21
7220
发布2020-01-06 11:29:21
举报
文章被收录于专栏:python3python3

一个Future是用来表示将来要完成的结果,异步循环可以自动完成对这种对象的状态触发,例子如下:

代码语言:javascript
复制
import asyncio


def mark_done(future, result):
    print('setting future result to {!r}'.format(result))
    future.set_result(result)


event_loop = asyncio.get_event_loop()
try:
    all_done = asyncio.Future()

    print('scheduling mark_done')
    event_loop.call_soon(mark_done, all_done, 'the result')

    print('entering event loop')
    result = event_loop.run_until_complete(all_done)
    print('returned result: {!r}'.format(result))
finally:
    print('closing event loop')
    event_loop.close()

print('future result: {!r}'.format(all_done.result()))

输出结果如下:

scheduling mark_done entering event loop setting future result to 'the result' returned result: 'the result' closing event loop future result: 'the result'

在这个例子里,并没有调用return语句,但也可以生成一个结果返回。Future的使用跟协程使用是一样的。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档