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