name: actor-model-implementer description: ‘为并发计算实现actor模型。当需要时使用:(1) 构建并发系统,(2) 分布式编程,(3) 容错系统。’ version: 1.0.0 tags:
- 并发
- actor模型
- 分布式
- 消息传递 difficulty: 中级 languages:
- python
- rust
- erlang dependencies: []
Actor模型实现器
为并发计算实现actor模型。
何时使用
- 构建并发/分布式系统
- 实现容错系统
- 建模响应式系统
- Erlang/Elixir风格的并发
这个技能做什么
- 创建actors - 独立的计算实体
- 处理消息传递 - 异步通信
- 管理邮箱 - 消息队列
- 实现行为 - Actor状态机
使用示例
# 创建系统
system = ActorSystem("example")
# 生成计数器
counter_ref = system.spawn(CounterActor)
# 发送消息
counter_ref.tell(10) # 添加10
counter_ref.tell("get") # 查询计数
# 询问模式
def on_reply(count):
print(f"Count is: {count}")
# 获取回复
future = counter_ref.ask("get")
print(f"Count: {future.result()}")
# 生成ping-pong
ping = system.spawn(PingPongActor)
pong = system.spawn(PingPongActor)
ping.tell("ping", sender=pong)
# 关闭
system.stop()
关键概念
| 概念 | 描述 |
|---|---|
| Actor | 隔离计算,具有私有状态 |
| Mailbox | 消息队列 |
| Address | Actor引用(PID) |
| Message passing | 异步,无共享 |
| Behavior | 消息处理函数 |
| Supervision | 故障处理层次结构 |
Actor模式
- 发送即忘记 - 异步发送
- 请求-响应 - 询问并回复
- 管道 - 链式actors
- 发布/订阅 - 基于主题的消息传递
- 聚合器 - 收集结果
提示
- 保持消息不可变
- 避免在actors中阻塞
- 使用监督实现容错
- 考虑每个请求一个actor以实现隔离
- 监控邮箱大小
相关技能
software-transactional-memory- STM并发race-detection-tool- 检测竞态条件cps-transformer- 第一类延续
研究工具与成果
Actor模型实现:
| 系统 | 语言 | 学习内容 |
|---|---|---|
| Erlang/OTP | Erlang | 原始actor模型 |
| Akka | Scala/Java | 生产级actors |
| Erlang/Elixir | Elixir | 分布式actors |
| Scala Akka | Scala | 类型化actors |
| Pony | Pony | 基于能力的actors |
论文
- Hewitt, Bishop, Steiger (1973) - 原始actor模型论文 “A Universal Modular ACTOR Formalism for Artificial Intelligence”
- Agha (1986) - “Actors: A Model of Concurrent Computation in Distributed Systems”
- Armstrong - Erlang设计论文
研究前沿
1. 类型安全的Actors
- 挑战: 消息类型安全
- 方法: 类型化通道,会话类型
- 工具: Akka Typed, Pony
2. 分布式Actor框架
- 挑战: 位置透明性
- 方法: 远程化,集群管理
实现陷阱
| 陷阱 | 实际后果 | 解决方案 |
|---|---|---|
| 阻塞 | 邮箱堆积 | 异步操作 |
| 共享可变状态 | 竞态条件 | 不可变消息 |
| 死锁 | 系统停止 | 避免循环依赖 |