一、yiled
import time
# 任务1
def work1():
while True:
print("work1_start")
time.sleep(0.5)
yield
time.sleep(0.5)
print("work1_end")
# 任务2
def work2():
while True:
print("work2_start")
time.sleep(0.5)
yield
time.sleep(0.5)
print("work2_end")
w1 = work1()
w2 = work2()
while True:
next(w1)
next(w2)
二、greenlet
import time
import greenlet
# 任务1
def work1():
while True:
print("work1_start")
time.sleep(0.5)
w2.switch()
# 任务2
def work2():
while True:
print("work2_start")
time.sleep(0.5)
w1.switch()
w1 = greenlet.greenlet(work1)
w2 = greenlet.greenlet(work2)
while True:
w1.switch()
三(1)、gevent:不带monkey
因为没有使用monkey,所以系统里直接使用time.sleep无法生效。只能使用包自带的gevent.sleep
import time
import gevent
# 任务1
def work1(w):
print(w)
gevent.sleep(1)
print("w1 end")
# 任务2
def work2(w):
print(w)
gevent.sleep(1)
print("w2 end")
w1 = gevent.spawn(work1, "work1_start")
w2 = gevent.spawn(work2, "work2_start")
w1.join()
w2.join()
三(2)、gevent:带monkey
import gevent
import time
from gevent import monkey
# 打补丁,让gevent框架识别耗时操作,比如:time.sleep,网络请求延时
monkey.patch_all()
# 任务1
def work1(w):
print(w)
time.sleep(1)
print("w1-end")
# 任务1
def work2(w):
print(w)
time.sleep(1)
print("w2-end")
if __name__ == '__main__':
w1 = gevent.spawn(work1, "w1")
w2 = gevent.spawn(work2, "w2")
#阻塞等待两个协程执行完毕
gevent.joinall([w1, w2])
三(3) sock协程方式
import gevent
from gevent import monkey
# 次序为:先放monkey,后放需打补丁的引入
monkey.patch_socket()
from socket import *
# 打补丁,让gevent框架识别耗时操作,比如:time.sleep,网络请求延时
server_addr = ("127.0.0.1", 8080)
s = socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(server_addr)
s.listen(3)
def handle(c):
while True:
data = c.recv(128)
if not data:
break
print(data)
c.send(b"ok")
while True:
c, addr = s.accept()
print("connect from ", addr)
gevent.spawn(handle, c)