(python) gevent module (used by coroutines)

Gevent is a third-party library that makes it easy to implement concurrent synchronous or asynchronous programming with gevent.

usage:

g=vent.spawn(func,1,……,x=3,……)
#Create a coroutine object g, spawn the first parameter in parentheses is the function name, followed by multiple parameters (positional parameters, keyword parameters).
g.join()#Wait for the end
g.value#Get the return value of func.

Tasks will be automatically switched when IO blocking is encountered:

import guy

def f1():
    print('from f1 1')
    vent.sleep(3)
    print('from f1 2')

def f2():
    print('from f2 1')
    vent.sleep(2)
    print('from f2 2')

def f3():
    print('from f3 1')
    vent.sleep(2)
    print('from f3 2')

g1=vent.spawn(f1)
g2=gevent.spawn(f2)
g3=gevent.spawn(f3)

# g1.join()
# g2.join()
# g3.join()
vent.joinall([g1,g2,g3])

In the above example, gevent.sleep(2) simulates IO blocking that gevent can recognize.

And time.sleep() or other blocking, gevent can not directly identify, need the following line of code, patch identification.

from gevent import monkey;mokey.patch_all()

This line of code must be placed before the patcher. For convenience, it is better to place the square directly at the beginning of the file.

from gevent import monkey,spawn
monkey.patch_all()
import time

def f1():
    print('from f1 1')
    time.sleep(3)
    print('from f1 2')

def f2():
    print('from f2 1')
    time.sleep(2)
    print('from f2 2')

def f3():
    print('from f3 1')
    time.sleep(2)
    print('from f3 2')

g1=spawn(f1)
g2=spawn(f2)
g3=spawn(f3)

g1.join()
g2.join()
g3.join()

Next, let's use gevent to implement socket concurrency under a single thread.

Server:

from gevent import monkey ;monkey.patch_all()
from socket import *
import guy

def server(server_ip,port):
    s = socket (AF_INET, SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    s.bind((server_ip,port))
    s.listen(5)
    while True:
        conn,addr=s.accept()
        gevent.spawn(talk,conn,addr)

def talk(conn,addr):
    try:
        while True:
            res=conn.recv(1024)
            print('client %s:%s msg:%s ' %(addr[0],addr[1],res))
            conn.send(res.upper())
    except Exception as e :
        print (s)
    finally:
        conn.close()

if __name__ == '__main__':
    server('127.0.0.1',8080)

Client:

from threading import Thread
from socket import *
import threading
def client(server_ip,port):
    c=socket(AF_INET,SOCK_STREAM)#The socket object must be added to the function, otherwise it will be shared by other threads, otherwise other threads will share an object, then the client port will be the same.
    c.connect((server_ip,port))

    count=0
    while True:
        c.send(('%s say hello %s'%(threading.current_thread().getName(),count)).encode('utf-8'))
        msg=c.recv(1024)
        print(msg.decode('utf-8'))
        count+=1

if __name__ == '__main__':
    for i in range(100):
        t=Thread(target=client,args=('127.0.0.1',8080))
        t.start()

running result:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325751869&siteId=291194637