Python 學習筆記:協程
阿新 • • 發佈:2018-11-30
協程
1、 使用 greenlet 實現協程
from greenlet import greenlet def eat(): print('eating start') g2.switch() print('eating end') g2.switch() def play(): print('playing start') g1.switch() print('playing end') g1.switch() g1 = greenlet(eat) g2 = greenlet(play) g1.switch()
執行效果:
eating start
playing start
eating end
playing end
2 、 使用 gevent 實現協程。 注意第一句
from gevent import monkey; monkey.patch_all() 要放在其它匯入模組的上面,將把下面匯入模組的阻塞事件打包處理。
from gevent import monkey; monkey.patch_all() import time import gevent def eat(): print('eating start') time.sleep(1) print('eating end') def play(): print('playing start') time.sleep(1) print('playing end') g1 = gevent.spawn(eat) g2 = gevent.spawn(play) g1.join() g2.join()
輸出同例子1
3、協程的效果
from gevent import monkey; monkey.patch_all() import time import gevent def task(): time.sleep(1) print('doing job...') def sync1(): for i in range(10): task() def async1(): g_list=[] for i in range(10): g = gevent.spawn(task) g_list.append(g) gevent.joinall(g_list) #sync1() async1()
3、 利用協程爬取一些資訊
from gevent import monkey;monkey.patch_all() import gevent from urllib.request import urlopen def get_url(url1): res = urlopen(url1) html = res.read().decode('utf-8') return len(html) url_list = ['http://www.baidu.com', 'http://www.taobao.com', 'http://www.cnblogs.com', 'http://www.sina.com.cn', 'http://www.sohu.com'] g_list = [] for u in url_list: g_list.append(gevent.spawn(get_url,u)) gevent.joinall(g_list) for g in g_list: print(g.value, end=' ')
4、協程的TCP server
from gevent import monkey;monkey.patch_all() import socket import gevent sk = socket.socket() sk.bind(('127.0.0.1', 8090)) sk.listen() def chat(conn): conn.send(b'hello') msg = conn.recv(1024).decode('utf-8') print(msg) while True: conn, addr = sk.accept() gevent.spawn(chat, conn)
可以實現多工併發了。