高效能python編程之協程(stackless)

來源:互聯網
上載者:User
我們都知道並發(不是並行)編程目前有四種方式,多進程,多線程,非同步,和協程。

多進程編程在python中有類似C的os.fork,當然還有更高層封裝的multiprocessing標準庫,在之前寫過的python高可用程式設計方法http://www.cnblogs.com/hymenz/p/3488837.html中提供了類似nginx中master process和worker process間訊號處理的方式,保證了業務進程的退出可以被主進程感知。

多線程編程python中有Thread和threading,在linux下所謂的線程,實際上是LWP輕量級進程,其在核心中具有和進程相同的調度方式,有關LWP,COW(寫時拷貝),fork,vfork,clone等的資料較多,這裡不再贅述。

非同步在linux下主要有三種實現select,poll,epoll,關於非同步不是本文的重點。

說協程肯定要說yield,我們先來看一個例子:

#coding=utf-8import timeimport 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異常。

通過上面的例子我們看到協程的調度對於核心來說是不可見的,協程間是協同調度的,這使得並發量在上萬的時候,協程的效能是遠高於線程的。

import stacklessimport urllib2def output():    while 1:        url=chan.receive()        print url        f=urllib2.urlopen(url)        #print f.read()        print stackless.getcurrent()     def input():    f=open('url.txt')    l=f.readlines()    for i in l:        chan.send(i)chan=stackless.channel()[stackless.tasklet(output)() for i in xrange(10)]stackless.tasklet(input)()stackless.run()

關於協程,可以參考greenlet,stackless,gevent,eventlet等的實現。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.