定义一个Actor任务-python cookbook(第3版)高清中文完整版

时间:2021-06-10 05:20:03
【文件属性】:
文件名称:定义一个Actor任务-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2021-06-10 05:20:03
python cookbook 第3版 高清 中文完整版 12.10 定义一个Actor任务 问题 You’d like to define tasks with behavior similar to “actors” in the so-called “actor model.” 解决方案 The “actor model” is one of the oldest and most simple approaches to concurrency and distributed computing. In fact, its underlying simplicity is part of its appeal. In a nutshell, an actor is a concurrently executing task that simply acts upon messages sent to it. In response to these messages, it may decide to send further messages to other actors. Communication with actors is one way and asynchronous. Thus, the sender of a message does not know when a message actually gets delivered, nor does it receive a response or acknowledgment that the message has been processed. Actors are straightforward to define using a combination of a thread and a queue. For example: from queue import Queue from threading import Thread, Event # Sentinel used for shutdown class ActorExit(Exception): pass class Actor: def __init__(self): self._mailbox = Queue() def send(self, msg): ‘’’ Send a message to the actor ‘’’ self._mailbox.put(msg) def recv(self): ‘’’ Receive an incoming message ‘’’ msg = self._mailbox.get() if msg is ActorExit: raise ActorExit() return msg

网友评论