" "
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