当前位置:网站首页>Kotlin shared mutable state and concurrency
Kotlin shared mutable state and concurrency
2022-06-24 13:53:00 【day_ moon】
//1. Problems caused by concurrency suspend fun masRun(action:suspend()->Unit){ val a=100 val b=1000 val time= measureTimeMillis { coroutineScope { repeat(a){ launch { repeat(b){action()} } } } } println("actions: ${a * b} , Time $time ")//actions 100000 Time 49-80ms } @Volatile//Volatiles It is not useful var count=0 fun main_masRun() = runBlocking { withContext(Dispatchers.Default){ masRun{ count++ } } println(" total = $count")//68147 counter Without any synchronization } //2. Thread safe data structure to solve concurrency problem suspend fun masVolatile (action:suspend()->Unit){ val a=100 val b=1000 val time= measureTimeMillis { coroutineScope { repeat(a){ launch { repeat(b){action()} } } } } println("actions: ${a * b} , Time $time ")//actions 100000 Time 52 } var counts=AtomicInteger()//Volatiles It is not useful fun main_volatile () = runBlocking { withContext(Dispatchers.Default){ masVolatile{ counts.incrementAndGet()// It used to be ++ } } println(" total = $counts")//100000 } //3. Limit threads to fine-grained val counterContext= newSingleThreadContext("counterContext") fun main_countercontext() = runBlocking { withContext(Dispatchers.Default){ masVolatile{ withContext(counterContext){// Each individual value-added operation uses withContext(counterContext) count++ } } } println(" total = $count")//100000 } //4. Restrict threads with coarse granularity val counterContexts= newSingleThreadContext("counterContext") fun main_countercontexts() = runBlocking { withContext(counterContexts){// Thread restrictions are performed over a wide range masVolatile{ count++ } } println(" total = $count")//100000 4152 } //5. Mutually exclusive val mutex= Mutex() fun main_mutex() = runBlocking { withContext(Dispatchers.Default){// Thread restrictions are performed over a wide range masVolatile{ mutex.withLock {// Lock Fine grained count++ } } } println(" total = $count")//100000 4152 } //6.Actors sealed class CounterMsg object IncCounter : CounterMsg()// Added objects class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg()// A response to a request fun CoroutineScope.counterActor() = actor<CounterMsg> { var counter = 0 // actor state for (msg in channel) { // iterate over incoming messages when (msg) { is IncCounter -> counter++ is GetCounter -> msg.response.complete(counter) } } } fun main_actor() = runBlocking<Unit> { val counter = counterActor() // Add one more actor withContext(Dispatchers.Default) { masVolatile { counter.send(IncCounter) } } // from actor Get the value sent val response = CompletableDeferred<Int>() counter.send(GetCounter(response)) println("Counter = ${response.await()}") counter.close() // close actor }
边栏推荐
- Developer survey: rust/postgresql is the most popular, and PHP salary is low
- 2022 Quality Officer - Equipment direction - post skills (Quality Officer) recurrent training question bank and online simulation examination
- kotlin 匿名函数 与 Lambda
- PM should also learn to reflect every day
- 4个不可不知的“安全左移”的理由
- 服务可见可观测性
- 谷歌WayMo提出R4D: 采用参考目标做远程距离估计
- Operation of simulated test question bank and simulated test platform for safety production management personnel of fireworks and firecrackers production units in 2022
- 数学之英文写作——基本中英文词汇(几何与三角的常用词汇)
- Rasa 3.x 学习系列-非常荣幸成为 Rasa contributors 源码贡献者,和全世界的Rasa源码贡献者共建共享Rasa社区!
猜你喜欢
10 个 Reduce 常用“奇技淫巧”
Developer survey: rust/postgresql is the most popular, and PHP salary is low
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
常识知识点
杰理之红外滤波【篇】
【5G NR】5G NR系统架构
杰理之串口接收 IO 需要设置数字功能【篇】
Vulnerability management mistakes that CIOs still make
Seven challenges faced by data scientists and Solutions
The research on the report "market insight into China's database security capabilities, 2022" was officially launched
随机推荐
MIT-6.824-lab4A-2022(万字讲解-代码构建)
Kotlin keyword extension function
Vulnerability management mistakes that CIOs still make
Cloud native essay solicitation progress case practice
项目经理的晋级之路
Developer survey: rust/postgresql is the most popular, and PHP salary is low
《中国数据库安全能力市场洞察,2022》报告研究正式启动
Android kotlin Encyclopedia
HarmonyOS-3
国内首款开源MySQL HTAP数据库即将发布,三大看点提前告知
吉时利静电计宽测量范围
首席信息安全官仍然会犯的漏洞管理错误
Gatling 性能测试
kotlin 匿名函数 与 Lambda
2022年氟化工艺考试模拟100题及答案
Dragon lizard developer said: first time you got an electric shock, so you are such a dragon lizard community| Issue 8
常识知识点
图扑软件数字孪生海上风电 | 向海图强,奋楫争先
kotlin 组合挂起函数
NPM package [details] (including NPM package development, release, installation, update, search, uninstall, view, version number update rules, package.json details, etc.)