Python co-process

Source: Internet
Author: User

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

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.