Python3 co-process

Source: Internet
Author: User
Tags switches

" "
co-process
No switching consumption
implementation of concurrency, Concurrency: not thread-cutting, but the task of the thread to switch, if you switch tasks directly, is also concurrent
Cons: Cannot take advantage of multi-core
co-process is the focus, the implementation of multiple concurrency, packaging a lot of good modules, post-application
" "

The basic implementation of the co-process
Import Timedefconsumer (): R="'     whiletrue:n=yieldRPrint('[consumer]<<consuming%s ...'%N) time.sleep (1) R='OK'defProduce (c): Next (c) n=0 whileN < 5: N= n + 1Print('[producer]>>producing%s ...'%N) CR=c.send (n)Print('[Producer]>>consumer return:%s'%CR)if __name__=='__main__': C=consumer () produce (c)

‘‘‘
Greenlet
Less common, only tasks, but not time-saving for IO-intensive tasks
‘‘‘
 from Import Greenlet def test1 ():     Print (    gr2.switch)print()    gr2.switch ()def  Test2 ( ):    print(    gr1.switch)print(  = Greenlet (test2) gr1.switch ()

‘‘‘
Gevent
Third-party libraries
When an greenlet encounters an IO operation, such as accessing the network, it automatically switches to the other Greenlet, waits until the IO operation is complete, and then switches back to continue at the appropriate time.
‘‘‘
ImportRequests,gevent,time fromGeventImportMonkeymonkey.patch_all ()#since the switchover is done automatically during IO operations, Gevent needs to modify some of the standard libraries that Python comes with, which is done by monkey patch at startupdeffoo (URL): Response=requests.get (URL) response_str=Response.textPrint("GET Data%s"%Len (response_str), URL) s=time.time () Gevent.joinall ([Gevent.spawn (foo),"https://itk.org/"), Gevent.spawn (foo,"https://www.github.com/")])                #gevent.spawn (foo, "https://zhihu.com/")])Print(Time.time ()-s)

Python3 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.