当前位置:网站首页>深潜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。
边栏推荐
- Memory escape analysis
- [deep learning] common methods for deep learning to detect small targets
- pytorch 筆記 torch.nn.BatchNorm1d
- Implementation of iterative method for linear equations
- Musk has more than 100 million twitter fans, but he has been lost online for a week
- 智能DNA分子纳米机器人模型来了
- R语言plotly可视化:使用plotly可视化多分类模型的预测置信度、模型在2D网格中每个数据点预测的置信度、置信度定义为在某一点上最高分与其他类别得分之和之间的差值
- 马斯克推特粉丝过亿了,但他在线失联已一周
- CSDN blog operation team 2022 H1 summary
- 内存逃逸分析
猜你喜欢

Mysql database foundation: constraint and identification columns

mysql数据库基础:存储过程和函数

Apple's 5g chip was revealed to have failed in research and development, and the QQ password bug caused heated discussion. Wei Lai responded to the short selling rumors. Today, more big news is here

RobotFramework学习笔记:环境安装以及robotframework-browser插件的安装

透过华为军团看科技之变(五):智慧园区

Retest the cloud native database performance: polardb is still the strongest, while tdsql-c and gaussdb have little change

Review of mathematical knowledge: curve integral of the second type

19:00 p.m. tonight, knowledge empowerment phase 2 live broadcast - control panel interface design of openharmony smart home project

Voir le changement technologique à travers la Légion Huawei (5): Smart Park

Matplotlib notes: contour & Contour
随机推荐
ArcGIS Pro脚本工具(6)——修复CAD图层数据源
苹果高管公然“开怼”:三星抄袭 iPhone,只加了个大屏
19:00 p.m. tonight, knowledge empowerment phase 2 live broadcast - control panel interface design of openharmony smart home project
腾讯云数据库工程师能力认证重磅推出,各界共话人才培养难题
【Proteus仿真】Arduino UNO LED模拟交通灯
ArcGIS Pro scripting tool (5) - delete duplicates after sorting
Go -- standard library sort package
安徽《合肥市装配式建筑施工图审查设计深度要求》印发;河北衡水市调整装配式建筑预售许可标准
Notes on numerical calculation - iterative solution of linear equations
R语言aov函数进行重复测量方差分析(Repeated measures ANOVA、其中一个组内因素和一个组间因素)、分别使用interaction.plot函数和boxplot对交互作用进行可视化
微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条...
历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并
从0使用keil5软件仿真调试GD32F305
SGD has many improved forms. Why do most papers still use SGD?
LVGL 8.2 Checkboxes as radio buttons
Qt之实现动效导航栏
【Rust每周一库】num-bigint - 大整数
Test memory read rate
Kernel linked list (general linked list) "list.h" simple version and individual comments
Agile Development: super easy to use bucket estimation system