协程之yield
#coding=utf-8
import time
def A():
while True:
print('---A---')
yield
time.sleep(0.5)
def B(c):
while True:
print('---B---')
next(c)
time.sleep(0.5)
if __name__ == '__main__':
a=A()
B(a)
[chaoge@localhost mypython]$ python3 coroutine01.py
---B---
---A---
---B---
---A---
---B---
---A---
协程之greenlet
#安装greenlet:pip3 install greenlet
#coding=utf-8
from greenlet import greenlet
import time
def coroutine1():
while True:
print('---A---')
gr2.switch()
time.sleep(0.5)
def coroutine2():
while True:
print('---B---')
gr1.switch()
time.sleep(0.5)
gr1 = greenlet(coroutine1)
gr2 = greenlet(coroutine2)
gr1.switch()
[chaoge@localhost mypython]$ python3 greenlet01.py
---A---
---B---
---A---
---B---
---A---
---B---
---A---
---B---
---A---
协程之gevent
#coding=utf-8
#安装:pip3 install gevent
import gevent
def f(n):
for i in range(n):
print(gevent.getcurrent(),i)
#遇到耗时操作,自动切换
gevent.sleep(1)
g1 = gevent.spawn(f,5)
g2 = gevent.spawn(f,5)
g3 = gevent.spawn(f,5)
g1.join()
g2.join()
g3.join()
[chaoge@localhost mypython]$ python3 gevent01.py <Greenlet at 0x7f43ce24fc28: f(5)> 0
<Greenlet at 0x7f43c6f59930: f(5)> 0
<Greenlet at 0x7f43c6f599c8: f(5)> 0
<Greenlet at 0x7f43ce24fc28: f(5)> 1
<Greenlet at 0x7f43c6f59930: f(5)> 1
<Greenlet at 0x7f43c6f599c8: f(5)> 1
<Greenlet at 0x7f43ce24fc28: f(5)> 2
<Greenlet at 0x7f43c6f59930: f(5)> 2
<Greenlet at 0x7f43c6f599c8: f(5)> 2
<Greenlet at 0x7f43ce24fc28: f(5)> 3
<Greenlet at 0x7f43c6f59930: f(5)> 3
<Greenlet at 0x7f43c6f599c8: f(5)> 3
<Greenlet at 0x7f43ce24fc28: f(5)> 4
<Greenlet at 0x7f43c6f59930: f(5)> 4
<Greenlet at 0x7f43c6f599c8: f(5)> 4
#coding=utf-8
#gevent版-TCP并发服务器
import sys
import time
import gevent
#导入gevent中的socket
from gevent import socket,monkey
#打补丁
monkey.patch_all()
def handle_request(conn):
while True:
#等待客户端发送数据(阻塞,即为耗时操作),自动切换到另一个协程
data = conn.recv(1024)
if not data:
conn.close
break
print("recv:",data)
conn.send(data)
def server(port):
s = socket.socket()
s.bind(("",port))
s.listen(5)
while True:
#等待客户端连接
cli,addr = s.accept()
#创建一个协程
gevent.spawn(handle_request,cli)
if __name__ == '__main__':
server(7788)
[chaoge@localhost mypython]$ python3 gevent02.py recv: b'hello'
recv: b'hello'
recv: b'hello'