1,如何實如今兩個函數之間的切換?app
def func1(): print(l) yield print(3) yield def func2(): g =func1() next(g) print(2) next(g) print(4) func2()
2,協程異步
import time from greenlet import greenlet # 在單線程中切換狀態的模塊 def eat1(): print('吃雞腿1') g2.switch() time.sleep(5) print('吃雞翅2') g2.switch() def eat2(): print('吃餃子1') g1.switch() time.sleep(3) print('白切雞') g1 = greenlet(eat1) g2 = greenlet(eat2) g1.switch()
3,geventsocket
from gevent import monkey;monkey.patch_all() import time # time socket urllib requests import gevent # greenlet gevent在切換程序的基礎上又實現了規避IO from threading import current_thread def func1(): print(current_thread().name) print(123) time.sleep(1) print(456) def func2(): print(current_thread().name) # dummythread print('hahaha') time.sleep(1) print('10jq') g1 = gevent.spawn(func1) # 碰見他認識的io會自動切換的模塊 g2 = gevent.spawn(func2) gevent.joinall([g1,g2])
4,效率對比async
from gevent import monkey;monkey.patch_all() import time # time socket urllib requests import gevent # greenlet gevent在切換程序的基礎上又實現了規避IO def task(args): time.sleep(1) print(args) def sync_func(): # 同步 for i in range(10): task(i) def async_func(): # 異步 g_l = [] for i in range(10): g_l.append(gevent.spawn(task,i)) # 給寫成任務傳參數 gevent.joinall(g_l) start = time.time() sync_func() print(time.time() - start) start = time.time() async_func() print(time.time() - start)