程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Master gevent module of learning notes for Python introductory development

編輯:Python

The point of this section

master gevent modular
The duration of this section needs to be controlled 15 Within minutes

One gevent modular

 install
pip3 install gevent

Gevent It's a third-party library , Easy access gevent Implement concurrent synchronous or asynchronous programming , stay gevent The main pattern used in is Greenlet, It is a C Expansion module access Python Lightweight process of . Greenlet All run inside the main program operating system process , But they are co scheduled .

# usage
g1=gevent.spawn(func,1,,2,3,x=4,y=5) Create a process object g1,spawn The first argument in parentheses is the function name , Such as eat, There can be more than one parameter , It can be a positional argument or a keyword argument , It's all passed to functions eat Of
g2=gevent.spawn(func2)
g1.join() # wait for g1 end
g2.join() # wait for g2 end
# Or one step of cooperation :gevent.joinall([g1,g2])
g1.value# Get func1 The return value of

encounter IO Automatically switch tasks when blocked

import gevent
def eat(name):
print('%s eat 1' %name)
gevent.sleep(2)
print('%s eat 2' %name)
def play(name):
print('%s play 1' %name)
gevent.sleep(1)
print('%s play 2' %name)
g1=gevent.spawn(eat,'egon')
g2=gevent.spawn(play,name='egon')
g1.join()
g2.join()
# perhaps gevent.joinall([g1,g2])
print(' Lord ')

The above example gevent.sleep(2) The simulation is gevent Recognizable io Blocking ,

and time.sleep(2) Or other blockages ,gevent It can't be directly recognized by using the following line of code , patch up , You can recognize

from gevent import monkey;monkey.patch_all() Must be placed in front of the patched person , Such as time,socket Module before

Or we can just remember : Use gevent, Need to put from gevent import monkey;monkey.patch_all() Put it at the beginning of the file

from gevent import monkey;monkey.patch_all()
import gevent
import time
def eat():
print('eat food 1')
time.sleep(2)
print('eat food 2')
def play():
print('play 1')
time.sleep(1)
print('play 2')
g1=gevent.spawn(eat)
g2=gevent.spawn(play_phone)
gevent.joinall([g1,g2])
print(' Lord ')

We can use threading.current_thread().getName() To see each g1 and g2, The result is DummyThread-n, Namely false thread

Two practice

adopt gevent Realize the socket Concurrent (from gevent import monkey;monkey.patch_all() Be sure to put it in the import socket Module before , otherwise gevent Can't recognize socket The block )

Server side

from gevent import monkey;monkey.patch_all()
from socket import *
import gevent
# If you don't want to use money.patch_all() patch up , It can be used gevent Self contained socket
# from gevent import socket
# s=socket.socket()
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(e)
finally:
conn.close()
if __name__ == '__main__':
server('127.0.0.1',8080)

Multithreading concurrent multiple clients

from threading import Thread
from socket import *
import threading
def client(server_ip,port):
c=socket(AF_INET,SOCK_STREAM) # Socket objects must be added to functions , In the local namespace , It is shared by all threads outside the function , Then we share a socket object , Then the client port will always 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(500):
t=Thread(target=client,args=('127.0.0.1',8080))
t.start()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved