当前位置:网站首页>深潜Kotlin协程(十七):演员
深潜Kotlin协程(十七):演员
2022-06-30 10:09:00 【RikkaTheWorld】
系列电子书:传送门
在计算机科学中,有一种并发模型,称为演员模式(actor model),其最重要的概念就是演员,它是一个计算机实体,响应接收到的消息,它可以并发下面行为:
- 向其他演员发送有限数量的信息
- 创造有限数量的新演员
- 指定接收到下一个信息时应该发生行为
演员可以修改自己的私有状态,但只能通过消息传递间接的影响其它演员,因此不需要同步它们。每个演员运行在单个线程上,一个接一个地处理消息。
在 Kotlin 协程中,我们可以很容易地实现这个模型。我们使用 channel 将消息队列同步到演员上,然后我们只需要一个接一个处理这些消息的协程。在下面的代码片段中,你可以看到我们的 massiveRun 问题用演员模型解决了:
sealed class CounterMsg
object IncCounter : CounterMsg()
class GetCounter(
val response: CompletableDeferred<Int>
) : CounterMsg()
fun CoroutineScope.counterActor(): Channel<CounterMsg> {
val channel = Channel<CounterMsg>()
launch {
var counter = 0
for (msg in channel) {
when (msg) {
is IncCounter -> {
counter++
}
is GetCounter -> {
msg.response.complete(counter)
}
}
}
}
return channel
}
suspend fun main(): Unit = coroutineScope {
val counter: SendChannel<CounterMsg> = counterActor()
massiveRun {
counter.send(IncCounter) }
val response = CompletableDeferred<Int>()
counter.send(GetCounter(response))
println(response.await()) // 1000000
counter.close()
}
这里不存在同步问题,因为演员在单个线程上工作。
为了简化这个模型,有一个 actor 协程构建器,它做了上述所示的事情(创建一个 channel 并启动一个协程),并为异常处理提供了更好的支持(例如,出现异常时会自行关闭 channel)。
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0
for (msg in channel) {
when (msg) {
is IncCounter -> counter++
is GetCounter -> msg.response.complete(counter)
}
}
}
总结
演员模型是并行处理的一个重要模型。它目前在 Kotlin 中并不流行,但值得我们去了解,因为有一些案例完全适合使用它们,在这个模型中,最重要的概念是演员,它是响应消息的计算实体。因为它只操作一个协程,所以访问它的状态并没有冲突。我们可以用可能提供持久性或优先级的标准功能包装演员,从而创造许多有趣的可能。
曾经有一段时间,角色模型作为设计后端应用程序的一种主流方法(就像 Akka 一样),但在我看来,这似乎不是现在的趋势,我的观点是,这是因为大多数开发者更喜欢使用特别队列或流软件,如 Kafka 或 RabbitMQ。
边栏推荐
- mysql数据库基础:视图、变量
- Compétences Comb 27 @ Body sense Manipulator
- js常见问题
- Auto Seg-Loss: 自动损失函数设计
- "Hackers and painters" -- why not be stupid
- Ionic4 drag the ion reorder group component to change the item order
- Using LVM to resize partitions
- June training (day 30) - topology sorting
- R语言aov函数进行重复测量方差分析(Repeated measures ANOVA、其中一个组内因素和一个组间因素)、分别使用interaction.plot函数和boxplot对交互作用进行可视化
- Overview of currency
猜你喜欢

再测云原生数据库性能:PolarDB依旧最强,TDSQL-C、GaussDB变化不大
[email protected]+ Alibaba cloud +nbiot+dht11+bh1750+ soil moisture sensor +oled"/>Skill sorting [email protected]+ Alibaba cloud +nbiot+dht11+bh1750+ soil moisture sensor +oled

nvm、nrm、npx使用(安装、基本命令、参数、curl、wget)

马斯克推特粉丝过亿了,但他在线失联已一周

Mysql database foundation: views and variables

Qt之实现动效导航栏

吴恩达2022机器学习专项课测评来了!

CSDN博客运营团队2022年H1总结

Compétences Comb 27 @ Body sense Manipulator

IPhone address book import into Excel
随机推荐
RobotFramework学习笔记:环境安装以及robotframework-browser插件的安装
Go -- standard library sort package
matplotlib 笔记: contourf & contour
Circuit breaker hystrixcircuitbreaker
Remember the experience of an internship. It is necessary to go to the pit (I)
R语言plotly可视化:使用plotly可视化多分类模型的预测置信度、模型在2D网格中每个数据点预测的置信度、置信度定义为在某一点上最高分与其他类别得分之和之间的差值
技能梳理[email protected]在oled上控制一条狗的奔跑
[rust daily] several new libraries were released on January 23, 2021
Typescript – classes in Es5, inheritance, static methods
Q-Learning笔记
R language plot visualization: use plot to visualize the prediction confidence of the multi classification model, the prediction confidence of each data point of the model in the 2D grid, and the conf
Notes on numerical calculation - iterative solution of linear equations
【深度学习】深度学习检测小目标常用方法
腾讯云数据库工程师能力认证重磅推出,各界共话人才培养难题
mysql数据库基础:存储过程和函数
LVGL 8.2 Image
SGD有多种改进的形式,为什么大多数论文中仍然用SGD?
JS FAQs
Ionic4 drag the ion reorder group component to change the item order
[rust daily] the first rust monthly magazine on January 22, 2021 invites everyone to participate