高性能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

相关文章
相关标签/搜索