Explanation of python Task in Synergetic Call Example

  • 2021-11-02 01:21:33
  • OfStack

1. Description

Tasks is used for concurrent scheduling of co-routines, and Task objects are created through asyncio.create_task (co-routine objects), so that co-routines can join the event loop and wait for scheduling execution. In addition to using the asyncio. create_task () function, you can also use the low-level loop.create_task () or ensure_future () functions. Manual instance Task object is recommended.

2. Pay attention to use

Added to the asyncio. create_task function in Python3.7. Prior to Python3.7, you could use the low-level asyncio.ensure_future function.

3. Examples


import asyncio
 
 
async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return " Return value "
 
 
async def main():
    print("main Begin ")
    #  Create a synergy and encapsulate the synergy into the 1 A Task Object and immediately added to the task list of the event loop, waiting for the event loop to execute (the default is ready). 
    task1 = asyncio.create_task(func())
    #  Create a synergy and encapsulate the synergy into the 1 A Task Object and immediately added to the task list of the event loop, waiting for the event loop to execute (the default is ready). 
    task2 = asyncio.create_task(func())
    print("main End ")
    #  When executing a program encounters IO Operation, it automatically switches to perform other tasks. 
    #  Here await Is to wait for all the corresponding co-processes to be executed and get the results 
    ret1 = await task1
    ret2 = await task2
    print(ret1, ret2)
    
    
asyncio.run(main())

Extension of knowledge points:

python asyncio co-routine calls task step


import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

Related articles: