1.簡介
gevent是一個基於協程的Python網絡庫,它使用 greenlet在libev 或libuv事件循環之上提供高級同步API 。
功能包括:
- 基於libev或libuv的快速事件循環。
- 基於greenlets的輕量級執行單元。
- 重用Python標準庫中的概念的API(例如,有事件和 隊列)。
- 具有SSL支持的協作套接字
- 通過線程池,dnspython或c-ares執行的協作DNS查詢。
- 猴子修補實用程序,以使第三方模塊合作
- TCP / UDP / HTTP服務器
- 子流程支持(通過gevent.subprocess)
- 線程池
2.gevent安裝
pip install gevent
3.下面看一個例子
# -*- coding: utf-8 -*-
import datetime
import gevent
from gevent import monkey; monkey.patch_socket()
def func(hello_world_num):
print("-------begin func-------")
for j in range(hello_world_num):
print('gevent: %s, ====== j:%d, hello world!'% (gevent.getcurrent(),j))
#gevent.sleep(0)
print("-------end func-------")
def gevent_func(gevent_num,hello_world_num):
gevents=[]
a=datetime.datetime.now()
for num in range(gevent_num):
g1 = gevent.spawn(func, hello_world_num)
gevents.append(g1)
gevent.joinall(gevents)
b=datetime.datetime.now()
print('start time:%s,end time:%s,use time:%s'% (a,b,(b-a)))
#####調用事例#####
#協程數
gevent_num=3
#任務循環數
hello_world_num=5
gevent_func(gevent_num,hello_world_num)
來看一下執行結果(從結果裏可以看出,每個協程執行順序都是01234,一個協程執行完後纔會進入下一個):
4. 同步和異步執行
(1)併發的核心思想是,可以將更大的任務分解爲一組子任務,這些子任務被安排爲同時或異步運行,而不是一次一個或同步運行。兩個子任務之間的切換稱爲上下文切換。
(2)如果把上面的hello_world_num循環次數改爲500000,讓它們的運行時間長一點,然後在操作系統的進程管理器中看,線程數只有1個。
(3)一般我們採用gevent+多進程 處理高併發的操作,提升效率
(4)gevent中的上下文切換是通過yielding完成的。在這個例子中,我們通過 gevent.sleep(0)來切換上下文。
5.還是上面的例子 ,加gevent.sleep(0)看下效果
執行結果如下(和不加切換操作相比,協程間交替運行):
6.詳細教程網址
http://sdiehl.github.io/gevent-tutorial/
http://www.gevent.org/intro.html