当前位置:网站首页>深潜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。
边栏推荐
- Auto Seg-Loss: 自动损失函数设计
- JS FAQs
- Skill combing [email protected] control a dog's running on OLED
- 滴滴开源敏捷测试用例管理平台!
- 我在鹅厂淘到了一波“炼丹神器”,开发者快打包
- [deep learning] common methods for deep learning to detect small targets
- Anhui "requirements for design depth of Hefei fabricated building construction drawing review" was printed and distributed; Hebei Hengshui city adjusts the pre-sale license standard for prefabricated
- Smith chart view of semi steel coaxial RF line and RF line matching calibration of network analyzer e5071c
- 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
- LVGL 8.2 Checkboxes as radio buttons
猜你喜欢

小程序中读取腾讯文档的表格数据

我在鹅厂淘到了一波“炼丹神器”,开发者快打包
[email protected]体感机械臂"/>技能梳理[email protected]体感机械臂

RobotFramework学习笔记:环境安装以及robotframework-browser插件的安装
[email protected]语音模块+stm32+nfc"/>技能梳理[email protected]语音模块+stm32+nfc

CVPR 2022 | 清华&字节&京东提出BrT:用于视觉和点云3D目标检测的桥接Transformer

The intelligent DNA molecular nano robot model is coming

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

腾讯云数据库工程师能力认证重磅推出,各界共话人才培养难题

Compétences Comb 27 @ Body sense Manipulator
随机推荐
断路器HystrixCircuitBreaker
CSDN blog operation team 2022 H1 summary
再测云原生数据库性能:PolarDB依旧最强,TDSQL-C、GaussDB变化不大
[deep learning] common methods for deep learning to detect small targets
Skill combing [email protected] control a dog's running on OLED
技能梳理[email protected]體感機械臂
Input a decimal data, convert to 8, using the sequence stack
今晚19:00知识赋能第2期直播丨OpenHarmony智能家居项目之控制面板界面设计
苹果5G芯片被曝研发失败,QQ密码bug引热议,蔚来回应做空传闻,今日更多大新闻在此...
马斯克推特粉丝过亿了,但他在线失联已一周
Migrate full RT thread to gd32f4xx (detailed)
小程序中读取腾讯文档的表格数据
Machine learning interview preparation (I) KNN
Skill combing [email protected] somatosensory manipulator
Implementation of iterative method for linear equations
File sharing server
Musk has more than 100 million twitter fans, but he has been lost online for a week
The performance of arm's new CPU has been improved by 22%, up to 12 cores can be combined, and the GPU is first equipped with hardware optical tracking. Netizen: the gap with apple is growing
敏捷开发: 超级易用水桶估计系统
六月集训(第30天) —— 拓扑排序