当前位置:网站首页>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
}
原网站

版权声明
本文为[day_ moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241048331110.html