自從python2.2提供了yield關鍵字之後,python的生成器的很大一部分用途就是可以用來構建協同程式,能夠將函式掛起返回中間值並能從上次離開的地方繼續執行。python2www.cppcns.com.5的時候,這種生成器更加接近完全的協程,因為提供了將值和異常傳遞歸到乙個繼續執行的函式中,當等待生成器的時候,生成器能返回控制。
python提供的生成器設施:
python封裝
雖然python3提供了asyncio這樣的非同步io庫,而且也有greenlet等其他協程庫,但目前的需求並不是實際的網路io併發操作,而是需要模擬狀態機的執行,因此使用協程可以很方便的模擬,並加入認為的控制,下面是封裝的乙個python類。
class coroutine(object):
""" base class of the general coroutine object """
state_running = 0
state_waiting = 1
state_closing = 2
def __init__(self):
self.state = coroutine.state_waiting
self.started = false
self.args = none
self.routine = self._co()
def _co(self):
self.ret = none
while true:
semlwxbqblf.args = yield self.ret
if not self.started:
self.started = true
continue
else:
self.state = coroutine.state_running
self.ret = self.run(self.args)
if self.state == coroutine.state_closing:
break
self.state = coroutine.state_waiting
def start(self):
""" start the generator """
if self.routine is none:
raise runtimeerror('no task to start running!')
self.started = true
self.routine.next()
def finish(self):
""" finish the execution of this routine """
self.state = coroutine.state_closing
self.routine.close()程式設計客棧
def run(self, args):
""" the runing method to be executed every once time"""
raise notimplementederror
def execute(self, arg_obj):
""" awake this routine to execute once time """
return self.routine.send(arg_obj)
基於上述封裝,下面實現了乙個協同的生產者消費者示例:
class producercoroutine(coroutine):
""" the producer concrete coroutine """
def __init__(self, cnsmr):
if not isinstance(cnsmr, coroutine):
raise runtimeerror('consumer is not a coroutine object')
self.consumer = cnsmr
self.consumer.start()
super(producercoroutine, self).__init__()
def run(self, args):
print 'produce ', args
ret = self.consumer.execute(args)
print 'consumer return:', ret
def __call__(self, args):
""" custom method for the specific logic """
self.start()
while len(args) > 0:
p = args.pop()
self.execute(p)
self.finish()
class consumercoroutine(coroutine):
""" the consumer concrete coroutine """
def __init__(self):
super(consumercoroutine, self).__init__()
def run(self, args):
print 'consumer get args: ', args
return 'hahaha' + repr(args)
執行結果如下:
produce 4
consumer get ar 4
consumer return: hahaha4
produce 3
consumer get args: 3
consumer return: hahaha3
produce 2
consumer get args: 2
consumer return: hahaha2
produce 1
consumer get args: 1
consumer return: hahaha1
produce 0
consumer get args: 0
consumer return: hahaha0
本文標題: 基於python生成器封裝的協程類
本文位址:
Python 生成器,協程
生成器可以簡單有效的建立龐大的可迭代物件,而不需要在直接在記憶體中建立儲存整個序列 可以使用生成器推導式或者生成器函式來建立生成器 生成器函式返回資料時使用yield語句,而不是使用return def countdown n print counting down from d n while n...
python迭代器生成器協程
迭代器有兩個基本的方法 iter 和next 把乙個類作為乙個迭代器使用需要在類中實現兩個方法iter 與next stopiteration 異常用於標識迭代的完成 class mylist object def init self self.items def iter self iter my...
python 生成器協程運算例項
一 yield執行方式 我們定義乙個如下的生成器 def put on name print hi 貨物來了,準備搬到倉庫!format name while true goods yield print 貨物 s 已經被 s搬進倉庫了。goods,name p put on bigberg 輸出g...