ImportAsyncio@asyncio.coroutinedefAA (x):Print('1') b=yield fromxPrint(b) @asyncio. CoroutinedefBB ():Print('2') yield Print('3') return4x=BB () Loop=Asyncio.get_event_loop () loop.run_until_complete (AA (x)) Loop.close ()
The above can reveal the operation process of Ctrip created by the Asyncio module.
The @asyncio.coroutine provided with Asyncio can be used to mark a generator as a coroutine type, and then use yield from within coroutine to invoke another coroutine to implement asynchronous operations
The above code, Ctrip AA and Ctrip BB together constitute a pool, first AA execution, printing 1, execution to yield when the interruption, the computer to randomly execute the other Ctrip in the pool, because there are only two Ctrip, so on the implementation of BB, printing 2, resulting in an interruption, and then, Ctrip all the Ctrip in the pool has been interrupted, there is no executable ctrip, then the computer will not be interrupted forever, but one by one across the various ctrip yield to carry out the remaining code in Ctrip. Again, because the AA's execution needs to wait for the BB to complete the return (yield from x), then BB is always executed before AA. This prints 3 and then returns to Ctrip AA a 4,AA then prints 4
See this example for the concept of pool-carrying
ImportAsyncio@asyncio.coroutinedefd ():Print('D') yield Print('End') @asyncio. Coroutinedefe ():Print('e') yield@asyncio. Coroutinedeff ():Print('F') yield@asyncio. Coroutinedefg ():Print('g') yield@asyncio. Coroutinedefh ():Print('h') yield@asyncio. CoroutinedefJ ():Print('J') yieldLoop=Asyncio.get_event_loop () Tasks=[D (), E (), f (), g (), H (), J ()]loop.run_until_complete (asyncio.wait (Tasks)) Loop.close ()
‘‘‘
F
D
J
H
G
E
End
" "
Note that end is always the last to print, which means that only when all Ctrip in the Ctrip is interrupted, the computer crosses the yield in Ctrip and executes the remaining code in Ctrip.
Python co-process