python actor_基于Python 3.5异步的Actor模型

本文介绍了Python 3.5中的异步编程特性async/await,并展示了如何使用官方库asyncio实现异步Actor模型。通过示例代码演示了Ping-Pong场景,讨论了接收消息超时的处理以及如何扩展为发布-订阅者模式。同时指出,与Gevent的Actor相比,asyncio的Actor仅支持基于asyncio的库。
摘要由CSDN通过智能技术生成

Python 3.5异步模型

Python 3.5推出了async/await语法,在语法层面简化了异步编程。官方库asyncio是应用async/await的途径。

Ubuntu 16.04默认安装Python 3.5,或者通过pyenv安装它。

异步Actor的实现

基于asyncio,可以实现async actor.

import asyncioclass Actor(object):def __init__(self):self.inbox = asyncio.Queue()def send(self, message):self.inbox.put_nowait(message)async def receive(self, message):raise NotImplemented()async def run(self):self.running = Truewhile self.running:message = await self.inbox.get()await self.receive(message)

上述代码的关键是通过asyncio.Queue异步接收消息,并异步处理接收到的消息。

通过这个类,实现Ping-Pong示例:

import asynciofrom actor import Actorclass Pinger(Actor):async def receive(self, message):print(message)pong.send('ping')await asyncio.sleep(3)class Ponger(Actor):async def receive(self, message):print(message)ping.send('pong')await asyncio.sleep(3)ping = Pinger()pong = Ponger()p

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值