The Python coroutine asynchronous IO (II): asyncio use different methods to achieve coroutine

Introduction: In the last chapter we introduced the use from the source to the yield from the async, and finally to implement coroutines asyncio.wait () method, let's implement coroutine different control structures, let us look look at their different roles it ~

Coroutine plurality of linear control flow easily through the built-in keywords awaitto manage . Using the asynciomethod of the module can be realized more complicated structure, it can concurrently completed plurality coroutine.

一、asyncio.wait()

You can be one operation into multiple parts and performed separately, and wait(tasks)can be used to interrupt a collection of tasks (tasks) one of polled event loop to the task until the coroutine other background operations to complete before being awakened .

Import Time
 Import ASYNCIO 
the async DEF taskIO_1 ():
     Print ( ' started running ... IO task 1 ' ) 
    the await asyncio.sleep ( 2)   # Assuming that the time-consuming task 2S 
    Print ( ' IO task 1 has been completed, time-consuming 2S ' )
     return taskIO_1. __name__ 
the async DEF taskIO_2 ():
     Print ( ' starts running ... IO task 2 ' ) 
    the await asyncio.sleep ( 3)   # Assuming that the time-consuming task 3s 
    Print ( ' IO task 2 has been completed, time-consuming 3s ')
     Return taskIO_2. The __name__ 
the async DEF main (): # caller 
    Tasks = [taskIO_1 (), taskIO_2 ()]   # add tasks to the task all the 
    DONE, the await asyncio.wait = Pending (Tasks) # child producer 
    for R & lt in DONE: # DONE and a task is pending, the returned results need to individually call result () 
        Print ( ' coroutine disorder return value: ' + r.result ()) 

IF  the __name__ == ' __main__ ' : 
    Start = Time .time () 
    Loop = asyncio.get_event_loop ()# Create an event loop objects Loop 
    the try : 
        loop.run_until_complete (main ()) # completion of the event loop until the last end of the mission 
    a finally : 
        loop.close () # end of the event loop 
    Print ( ' all IO task total time% .5f s ' % a float (the time.time () - Start))

Execution results are as follows:

1 ... IO task starts running 
start running Task 2 ... IO 
IO Task 1 has been completed, time-consuming 2S 
IO Task 2 has been completed, time-consuming 3s 
coroutine disorderly return value: taskIO_2 
coroutine disorderly return value: taskIO_1 
All IO task total time 3.00209 seconds

[Explain]: wait () official documentation used as follows:

done, pending = await asyncio.wait(aws)

Here run concurrently incoming AWS (awaitable Objects), while by await returns a tuple containing (done, pending) of, DONE represents the task list has been completed , the Pending represents the task list is not complete .
Note:
① only when to wait () incoming timeout only possible when parameter pending list.
② through wait () returns a result set is in accordance with the event loop task completion order arranged, so that often the original order of the different tasks .

二、asyncio.gather()

If you are only concerned about the outcome of coroutines run concurrently collection, you can use gather()it not only by awaitreturns only one result set, and the result set order of results is the task of the incoming original order .

 

Import Time
 Import ASYNCIO 
the async DEF taskIO_1 ():
     Print ( ' started running ... IO task 1 ' ) 
    the await asyncio.sleep ( 3)   # Assuming that the time-consuming task 3S 
    Print ( ' IO task 1 has been completed, time-consuming 3S ' )
     return taskIO_1. __name__ 
the async DEF taskIO_2 ():
     Print ( ' starts running ... IO task 2 ' ) 
    the await asyncio.sleep ( 2)   # Assuming that the time-consuming task 2s 
    Print ( ' IO task 2 has been completed, time-consuming 2s ')
     Return taskIO_2. The __name__ 
the async DEF main (): # caller 
    resualts the await asyncio.gather = (taskIO_1 (), taskIO_2 ()) # child producer 
    Print (resualts) 

IF  the __name__ == ' __main__ ' : 
    Start = the time.time () 
    loop = asyncio.get_event_loop () # create an event loop objects loop 
    the try : 
        loop.run_until_complete (main ()) # completion of the event loop until the last end of the mission 
    a finally : 
        loop.close () # end of the event loop 
    print( ' All IO task total time in seconds% .5f ' % float (time.time () - Start))

Execution results are as follows:

IO task starts running ... 2 
starts running IO Task 1 ... 
IO Task 2 has been completed, time-consuming 2S 
IO task 1 has been completed, time-consuming 3S 
[ ' taskIO_1 ' , ' taskIO_2 ' ] 
all IO task total time 3.00184 second

[Explain]: gather()through awaitdirect returns a result set list, we can clearly see from the results came out, although the task 2 is completed first, but eventually returned the order of the result set is ranked in accordance with the initial task of the incoming order .

三、asyncio.as_completed()

as_completed(tasks)Is a generator , it manages a coroutine list (here is the incoming tasks) to run. When the task set lead in a task is finished, it will be the first by a awaitreturn to the task of keyword. Visible order and return the results wait()as are in accordance with the task order of.

Import Time
 Import ASYNCIO 
the async DEF taskIO_1 ():
     Print ( ' started running ... IO task 1 ' ) 
    the await asyncio.sleep ( 3)   # Assuming that the time-consuming task 3S 
    Print ( ' IO task 1 has been completed, time-consuming 3S ' )
     return taskIO_1. __name__ 
the async DEF taskIO_2 ():
     Print ( ' starts running ... IO task 2 ' ) 
    the await asyncio.sleep ( 2)   # Assuming that the time-consuming task 2s 
    Print ( ' IO task 2 has been completed, time-consuming 2s ')
     Return taskIO_2. __Name__ 
the async DEF main (): # caller 
    Tasks = [taskIO_1 (), taskIO_2 ()]   # Add all the tasks to task 
    for completed_task in asyncio.as_completed (Tasks): 
        resualt = the await completed_task # Generated is 
        Print ( ' coroutine disorder return value: ' + resualt) 

IF  the __name__ == ' __main__ ' : 
    Start = the time.time () 
    Loop = asyncio.get_event_loop () #Create an event loop objects Loop 
    the try : 
        loop.run_until_complete (main ()) # completion of the event loop until the last end of the mission 
    a finally : 
        loop.close () # end of the event loop 
    Print ( ' all IO task total time in seconds% .5f ' % a float (the time.time () - Start))

Execution results are as follows:

IO task starts running ... 2 
starts running IO Task 1 ... 
IO Task 2 has been completed, time-consuming 2s 
coroutine disorderly return value: taskIO_2 
IO Task 1 has been completed, time-consuming 3s 
coroutine disorderly return value: taskIO_1 
All IO task total time 3.00300 seconds

[Explain]: can be seen from the above procedure using as_completed (tasks) , and wait (tasks) in common is the return result order is the order of completion coroutine , which Gather () is just the opposite. The difference is that as_completed (tasks) can return to the real-time results of the current completed, and wait (tasks) need to wait to return after the end of all coroutines done to get results.

IV Summary

The following awsmeans:awaitable objects . That can wait for a set of objects , such as a coroutine is waiting for an object with a plurality of coroutine list a aws.

asyncio The main parameter passing Return value sequence awaitReturn Type Function Return Type
wait() aws Coroutine complete sequence

(done,pending)

Task list with two tuples

coroutine
as_completed() aws Coroutine complete sequence Return the original value Iterator
gather() *aws Parameter passing Task Order Return a list of values awaitable

 

Guess you like

Origin www.cnblogs.com/liugp/p/11074586.html