• asyncio模块中的Future和Task


     

     task是可以理解为单个coroutine,经过ensure_future方法处理而形成,而众多task所组成的集合经过asyncio.gather处理而形成一个future。

    再不精确的粗略的说,future就是存放着众多task或future的容器。

    而task又是future的子类,所以不管是task还是future还是coreture都可以看成是一个广义的携程,future无非是一个内部包含众多携程的大携程而已,await后面,task,coroture,future都可以接。

    ensure_future 可以将 coroutine 封装成 Task。

    asyncio.ensure_future(coro_or_future, *, loop=None)

    Schedule the execution of a coroutine object: wrap it in a future. Return a Task object.If the argument is a Future, it is returned directly.

    import asyncio
    async def hello(name):
        await asyncio.sleep(2)
        print('Hello, ', name)
    
    coroutine = hello("World")
    a = asyncio.ensure_future(coroutine)#
    print (a.__class__)#Task
    
    b=asyncio.Future()#标准future
    print (b.__class__)#Future
    
    print (issubclass(a.__class__,b.__class__))#true,Task类是Future类的子类
    
    #首先a是一个Task,又因为Task类是Futrue类的子类,所以,我们也可以说,a是一个Future
    
    
    #下面验证If the argument is a Future, it is returned directly.
    c=asyncio.ensure_future(b)#
    print (c is b)#true
    d=asyncio.ensure_future(a)#
    print (d is a)#True

     ----------------------------------------分割线----------------------------------------

    asyncio.gather 将一些 Future 和 coroutine 封装成一个 Future。

    asyncio.wait方法则返回一个 coroutine。

    run_until_complete 既可以接收 Future 对象,也可以是 coroutine 对象,如果是coroutine,则先把他转化为future

    BaseEventLoop.run_until_complete(future)

    Run until the Future is done.

    If the argument is a coroutine object, it is wrapped by ensure_future().

    Return the Future's result, or raise its exception.

  • 相关阅读:
    完整性检查工具Nabou
    Linux下使用网上银行
    戏说Linux商用数据库
    开源数据库“五虎将”
    搜寻Linux软件实用指南
    认识Linux瘦客户机
    一款开源Office软件---Lotus Symphony在Linux系统下的应用
    Leetcode-967 Numbers With Same Consecutive Differences(连续差相同的数字)
    Leetcode-965 Univalued Binary Tree(单值二叉树)
    Leetcode-966 Vowel Spellchecker(元音拼写检查器)
  • 原文地址:https://www.cnblogs.com/saolv/p/9860284.html
Copyright © 2020-2023  润新知