当前位置:网站首页>kotlin 共享可变状态和并发性
kotlin 共享可变状态和并发性
2022-06-24 12:58:00 【day_moon】
//1.并发引发的问题
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 ")//actions 100000 时间 49-80ms
}
@Volatile//Volatiles 是没有作用的
var count=0
fun main_masRun() = runBlocking {
withContext(Dispatchers.Default){
masRun{
count++
}
}
println("总数 = $count")//68147 counter而不进行任何同步
}
//2.线程安全的数据结构解决并发问题
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 ")//actions 100000 时间 52
}
var counts=AtomicInteger()//Volatiles 是没有作用的
fun main_volatile () = runBlocking {
withContext(Dispatchers.Default){
masVolatile{
counts.incrementAndGet()//之前是++
}
}
println("总数 = $counts")//100000
}
//3.以细粒度限制线程
val counterContext= newSingleThreadContext("counterContext")
fun main_countercontext() = runBlocking {
withContext(Dispatchers.Default){
masVolatile{
withContext(counterContext){//每个单独的增值操作都使用 withContext(counterContext)
count++
}
}
}
println("总数 = $count")//100000
}
//4.以粗粒度限制线程
val counterContexts= newSingleThreadContext("counterContext")
fun main_countercontexts() = runBlocking {
withContext(counterContexts){//线程限制是在比较大的范围内执行的
masVolatile{
count++
}
}
println("总数 = $count")//100000 4152
}
//5.互斥
val mutex= Mutex()
fun main_mutex() = runBlocking {
withContext(Dispatchers.Default){//线程限制是在比较大的范围内执行的
masVolatile{
mutex.withLock {//加锁 细粒度的
count++
}
}
}
println("总数 = $count")//100000 4152
}
//6.Actors
sealed class CounterMsg
object IncCounter : CounterMsg()//增加的对象
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg()//请求的回应
fun CoroutineScope.counterActor() = actor<CounterMsg> {
var counter = 0 // actor状态
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() //增加一个actor
withContext(Dispatchers.Default) {
masVolatile {
counter.send(IncCounter)
}
}
//从actor得到发送来的值
val response = CompletableDeferred<Int>()
counter.send(GetCounter(response))
println("Counter = ${response.await()}")
counter.close() //关闭actor
}边栏推荐
- Seven challenges faced by data scientists and Solutions
- 国内首款开源MySQL HTAP数据库即将发布,三大看点提前告知
- 青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
- One article explains R & D efficiency! Your concerns are
- kotlin 协程上下文和调度器
- 开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
- Vulnerability management mistakes that CIOs still make
- What is the difference between sap QM and UD for inspection lots with hum?
- Why does the kubernetes environment require that bridge NF call iptables be enabled?
- Prometheus PushGateway 碎碎念
猜你喜欢

How to avoid serious network security accidents?

AGCO AI frontier promotion (6.24)

10 个 Reduce 常用“奇技淫巧”

Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?

位于相同的分布式端口组但不同主机上的虚拟机无法互相通信

吉时利静电计宽测量范围

数据科学家面临的七大挑战及解决方法

Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team

图扑软件数字孪生海上风电 | 向海图强,奋楫争先

这几个默认路由、静态路由的配置部署都不会,还算什么网工!
随机推荐
首席信息安全官仍然会犯的漏洞管理错误
Eight major trends in the industrial Internet of things (iiot)
8 lines of code to teach you how to build an intelligent robot platform
Golden age ticket: Web3.0 Security Manual
Android kotlin Encyclopedia
AGCO AI frontier promotion (6.24)
Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
[sdx62] wcn685x IPA failure analysis and solution
Kotlin keyword extension function
3. caller service call - dapr
8 - Format integers and floating point numbers
Hands on data analysis unit 3 model building and evaluation
Activity生命周期
[log service CLS] Tencent cloud log service CLS accesses CDN
CPU status information us, sy and other meanings
Comparator 排序函数式接口
图扑软件数字孪生海上风电 | 向海图强,奋楫争先
Redis面试题
Mysql题目篇
2022年氟化工艺考试模拟100题及答案