神剑山庄资源网 Design By www.hcban.com
自从python2.2提供了yield关键字之后,python的生成器的很大一部分用途就是可以用来构建协同程序,能够将函数挂起返回中间值并能从上次离开的地方继续执行。python2.5的时候,这种生成器更加接近完全的协程,因为提供了将值和异常传递回到一个继续执行的函数中,当等待生成器的时候,生成器能返回控制。
python提供的生成器设施:
- yield:能够将自己挂起,并提供一个返回值给等待方
- send:唤起一个被挂起的生成器,并能够传递一个参数,可以在生成器中抛出异常
- next:本质上相当于send(None),对每个生成器的第一次调用必须不能传递参数
- close:主动退出一个生成器
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: self.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 args: 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,生成器,协程类
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无基于python生成器封装的协程类的评论...
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新日志
2024年10月01日
2024年10月01日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】