当前位置:网站首页>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
}边栏推荐
- Talk about GC of JVM
- Tupu software is the digital twin of offshore wind power, striving to be the first
- 详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
- 知识经济时代,教会你做好知识管理
- 吉时利静电计宽测量范围
- Prometheus pushgateway
- Autorf: learn the radiation field of 3D objects from single view (CVPR 2022)
- Jericho turns on shouting in all modes to increase mic automatic mute [chapter]
- How to manage tasks in the low code platform of the Internet of things?
- Ti Xing Shu'an joined the dragon lizard community to jointly create a network security ecosystem
猜你喜欢
随机推荐
数据科学家面临的七大挑战及解决方法
美国会参议院推进两党枪支安全法案
kotlin 数组、集合和 Map 的使用
kotlin 协程 lanch 详解
The project manager needs to look at six characteristics to build a team
Kotlin coordination channel
AntD checkbox,限制选中数量
返回新列表
发扬连续作战优良作风 全力以赴确保北江大堤安全
Jerry's serial port receiving IO needs to set the digital function [chapter]
杰理之无缝循环播放【篇】
Gatling 性能测试
Kotlin asynchronous flow
杰理之红外滤波【篇】
Kotlin anonymous function and lambda
【sdx62】WCN685X IPA注册失败问题分析及解决方案
【AI玩家养成记】用AI识别邻居家旺财是什么品种
Huawei PC grows against the trend, and product power determines everything
Daily question 8-515 Find the maximum value in each tree row
【sdx62】WCN685X IPA不生效问题分析及解决方案





![Jerry's infrared filtering [chapter]](/img/6b/7c4b52d39a4c90f969674a5c21b2c7.png)



