Thread and process operation is triggered by the program system interface, the final performer is the system, the operation of the association is artificial.
The significance of the existence of the process: for multi-threaded applications, the CPU by slicing the way to switch between threads of execution, thread switching takes time (save state, next continue). The co-process uses only one thread, which specifies the order in which a block of code is executed in one thread.
Usage scenarios for the coprocessor: when there is a large number of operations (IO) in the program that do not require the CPU, it is suitable for the association process.
Greenlet: Need to install in advance (PIP3 install Greenlet, after the installation of Greenlet Gevent also installed)
fromGreenletImportGreenletdeffoo1 ():Print('I am FOO1-GL1') Gl2.switch ()Print('Who am I?') Gl2.switch ()defFoo2 ():Print('I am FOO-GL2') Gl1.switch ()Print('Who am I?.') GL1=Greenlet (foo1) GL2=Greenlet (Foo2) gl1.switch ()Print('End')Greenlet
ImportGevent, timedeffoo ():Print('Running in Foo') gevent.sleep (0)#switch to another task with sleep Print('Explicit context Switch to Foo again.')defBar ():Print('Explicit Context Switch to back to bar') Gevent.sleep (1) Print('I woke up.')deffunc ():Print('Explicit Context Switch to Func.') gevent.sleep (0)Print('I am Come back') Gevent.joinall ([Gevent.spawn (foo), Gevent.spawn (bar), Gevent.spawn (func),])gevent
Automatic switching of IO operation encountered:
#Monkey.patch_all () to change the original socket to its own socket to send an HTTP request fromGeventImportmonkey; Monkey.patch_all ()ImportGevent, requestsdeff (URL):Print('Get:', url) resp=requests.get (URL) data=resp.text with open ('Test','W', encoding='Utf-8') as F:f.write (data)Print('%d bytes recceved from%s'%(len (data), URL)) Gevent.joinall ([Gevent.spawn (F,'https://www.baidu.com/'), Gevent.spawn (F,'https://www.yahoo.com/'), Gevent.spawn (F,'https://www.github.com/'),])
Python co-process