高性能python編程之協程

咱們都知道併發(不是並行)編程目前有四種方式,多進程,多線程,異步,和協程。
多進程編程在python中有相似C的os.fork,固然還有更高層封裝的multiprocessing標準庫,在以前寫過的python高可用程序設計方法中提供了相似nginx中master process和worker process間信號處理的方式,保證了業務進程的退出能夠被主進程感知。
多線程編程python中有Thread和threading,在linux下所謂的線程,其實是LWP輕量級進程,其在內核中具備和進程相同的調度方式,有關LWP,COW(寫時拷貝),fork,vfork,clone等的資料較多,這裏再也不贅述。
異步在linux下主要有三種實現select,poll,epoll,關於異步不是本文的重點。
說協程確定要說yield,咱們先來看一個例子:http://www.iplaypython.com/module/threading.htmlhtml

 import time
import sys
# 生產者
def produce(l):
    i=0
    while 1:
        if i < 5:
            l.append(i)
            yield i
            i=i+1
            time.sleep(1)
        else:
            return
      
# 消費者
def consume(l):
    p = produce(l)
    while 1:
        try:
            p.next()
            while len(l) > 0:
                print l.pop()
        except StopIteration:
            sys.exit(0)
l = []
consume(l)

 

在上面的例子中,當程序執行到produce的yield i時,返回了一個generator,當咱們在custom中調用p.next(),程序又返回到produce的yield i繼續執行,這樣l中又append了元素,而後咱們print l.pop(),直到p.next()引起了StopIteration異常。python

相關文章
相關標籤/搜索