码迷,mamicode.com
首页 > 编程语言 > 详细

Python3之greenlet&gevent模块

时间:2019-01-30 01:24:07      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:time   sock   enc   round   ==   hone   +=   name   border   

一.greenlet模块

简单实现单线程内的任务切换:

  1: import greenlet
  2: def eat(name):
  3:     print("%s eat 1" % name)
  4:     # 第二步
  5:     g2.switch("egon")
  6:     print("%s eat 2" % name)
  7:     # 第四步
  8:     g2.switch()
  9: def play(name):
 10:     print("%s play 1" % name)
 11:     # 第三步
 12:     g1.switch()
 13:     print("%s play 2" % name)
 14: g1 = greenlet.greenlet(eat)
 15: g2 = greenlet.greenlet(play)
 16: # 第一步
 17: g1.switch("egon")

对照结果:

  1: egon eat 1
  2: egon play 1
  3: egon eat 2
  4: egon play 2

注意单纯的切换(没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度。

二.gevent模块

Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程。

用法:

  1: g1=gevent.spawn(func,1,,2,3,x=4,y=5)创建一个协程对象g1,spawn括号内第一个参数是函数名,如eat,后面可以有多个参数,可以是位置实参或关键字实参,都是传给函数eat的
  2: 
  3: g2=gevent.spawn(func2)
  4: 
  5: g1.join() #等待g1结束
  6: 
  7: g2.join() #等待g2结束
  8: 
  9: #或者上述两步合作一步:gevent.joinall([g1,g2])
 10: 
 11: g1.value#拿到func1的返回值

遇到IO阻塞时会自动切换任务

  1: import gevent
  2: def eat(name):
  3:     print(‘%s eat 1‘ %name)
  4:     gevent.sleep(2)
  5:     print(‘%s eat 2‘ %name)
  6: def play(name):
  7:     print(‘%s play 1‘ %name)
  8:     gevent.sleep(1)
  9:     print(‘%s play 2‘ %name)
 10: g1=gevent.spawn(eat,‘egon‘)
 11: g2=gevent.spawn(play,name=‘egon‘)
 12: g1.join()
 13: g2.join()
 14: #或者gevent.joinall([g1,g2])
 15: print(‘回到主‘)

上例gevent.sleep(2)模拟的是gevent可以识别的io阻塞,

而time.sleep(2)或其他的阻塞,gevent是不能直接识别的需要用下面一行代码,打补丁,就可以识别了

from gevent import monkey;monkey.patch_all()必须放到被打补丁者的前面,如time,socket模块之前

  1: from gevent import monkey;monkey.patch_all()
  2: 
  3: import gevent
  4: import time
  5: def eat():
  6:     print(‘eat food 1‘)
  7:     time.sleep(2)
  8:     print(‘eat food 2‘)
  9: 
 10: def play():
 11:     print(‘play 1‘)
 12:     time.sleep(1)
 13:     print(‘play 2‘)
 14: 
 15: g1=gevent.spawn(eat)
 16: g2=gevent.spawn(play_phone)
 17: gevent.joinall([g1,g2])
 18: print(‘主‘)

通过gevent实现单线程下的socket并发(from gevent import monkey;monkey.patch_all()一定要放到导入socket模块之前,否则gevent无法识别socket的阻塞)

server

  1: from gevent import monkey;monkey.patch_all()
  2: from socket import *
  3: import gevent
  4: 
  5: #如果不想用money.patch_all()打补丁,可以用gevent自带的socket
  6: # from gevent import socket
  7: # s=socket.socket()
  8: 
  9: def server(server_ip,port):
 10:     s=socket(AF_INET,SOCK_STREAM)
 11:     s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
 12:     s.bind((server_ip,port))
 13:     s.listen(5)
 14:     while True:
 15:         conn,addr=s.accept()
 16:         gevent.spawn(talk,conn,addr)
 17: 
 18: def talk(conn,addr):
 19:     try:
 20:         while True:
 21:             res=conn.recv(1024)
 22:             print(‘client %s:%s msg: %s‘ %(addr[0],addr[1],res))
 23:             conn.send(res.upper())
 24:     except Exception as e:
 25:         print(e)
 26:     finally:
 27:         conn.close()
 28: 
 29: if __name__ == ‘__main__‘:
 30:     server(‘127.0.0.1‘,8080)

client

  1: from threading import Thread
  2: from socket import *
  3: import threading
  4: 
  5: def client(server_ip,port):
  6:     c=socket(AF_INET,SOCK_STREAM) #套接字对象一定要加到函数内,即局部名称空间内,放在函数外则被所有线程共享,则大家公用一个套接字对象,那么客户端端口永远一样了
  7:     c.connect((server_ip,port))
  8: 
  9:     count=0
 10:     while True:
 11:         c.send((‘%s say hello %s‘ %(threading.current_thread().getName(),count)).encode(‘utf-8‘))
 12:         msg=c.recv(1024)
 13:         print(msg.decode(‘utf-8‘))
 14:         count+=1
 15: if __name__ == ‘__main__‘:
 16:     for i in range(500):
 17:         t=Thread(target=client,args=(‘127.0.0.1‘,8080))
 18:         t.start()

Python3之greenlet&gevent模块

标签:time   sock   enc   round   ==   hone   +=   name   border   

原文地址:https://www.cnblogs.com/haoqirui/p/10336411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!