Python co-process

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.