協程,又稱微線程,纖程。協程是一種用戶態的輕量級線程。編程
協程擁有本身的寄存器上下文和棧。協程調度切換時,將寄存器上下文和棧保存到其餘地方,在切回來的時候,恢復先前保存的寄存器上下文和棧安全
協程能實現併發。併發
優勢:函數
缺點:高併發
yield 實現協程:spa
import time def consumer(): while True: n = yield #建立生成器函數,保存掛起和依據send傳值繼續該函數 if not n: return print('consumer--------consuming %s.....'%n) time.sleep(1) def producer(target): next(target) #初始化生成器函數 n = 0 while n < 5: n += 1 print('producer--------producing %s.....'%n) target.send(n) #傳值 target.close() if __name__ == '__main__': producer(consumer()) '''producer--------producing 1..... consumer--------consuming 1..... producer--------producing 2..... consumer--------consuming 2..... producer--------producing 3..... consumer--------consuming 3..... producer--------producing 4..... consumer--------consuming 4..... producer--------producing 5..... consumer--------consuming 5.....'''
greenlet 模塊實現協程線程
import greenlet def foo(): print('ok1') g2.switch() #switch 函數切換到g2對象 print('ok3') g2.switch() def bar(): print('ok2') g1.switch() print('ok4') g1 = greenlet.greenlet(foo) #建立greenlet 對象,傳入須要執行對函數 g2 = greenlet.greenlet(bar) if __name__ == '__main__': g1.switch() #啓動該函數
gevent 實現協程code
import gevent,time def foo(): print('ok1') gevent.sleep(1) print('ok3') def bar(): print('ok2') gevent.sleep(2) #模擬I/O操做 print('ok4') g1 = gevent.spawn(foo) #建立gevent對象 g2 = gevent.spawn(bar) gevent.joinall([g1,g2]) #運行 '''ok1 ok2 ok3 ok4'''