文件名称:定义一个Actor任务-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:43
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