上述就是android开发分享Android中的Coroutine协程原理解析的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
前言
协程是一个并发方案。也是一种思想。
传统意义上的协程是单线程的,面对io密集型任务他的内存消耗更少,进而效率高。但是面对计算密集型的任务不如多线程并行运算效率高。
不同的语言对于协程都有不同的实现,甚至同一种语言对于不同平台的操作系统都有对应的实现。
我们kotlin语言的协程是 coroutines for jvm的实现方式。底层原理也是利用java 线程。
基础知识
生态架构
相关依赖库
dependencies { // kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib:1.4.32" // 协程核心库 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3" // 协程android支持库 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3" // 协程java8支持库 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.4.3" // lifecycle对于协程的扩展封装 implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0" implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0" }
为什么一些人总觉得协程晦涩难懂?
1.网络上没有详细的关于协程的概念定义,每种语言、每个系统对其实现都不一样。可谓是众说纷纭,什么内核态用户态巴拉巴拉,很容易给我们带偏
2.kotlin的各种语法糖对我们造成的干扰。如:
- 高阶函数
- 源码实现类找不到
所以扎实的kotlin语法基本功是学习协程的前提。
实在看不懂得地方就反编译为java,以java最终翻译为准。
协程是什么?有什么用?
kotlin中的协程干的事就是把异步回调代码拍扁了,捋直了,让异步回调代码同步化。除此之外,没有任何特别之处。
创建一个协程,就是编译器背后偷偷生成一系列代码,比如说状态机。
通过挂起和恢复让状态机状态流转实现把层层嵌套的回调代码变成像同步代码那样直观、简洁。
它不是什么线程框架,也不是什么高深的内核态,用户态。它其实对于咱们安卓来说,就是一个关于回调函数的语法糖。。。
android开发分享Android中的Coroutine协程原理解析将会围绕挂起与恢复彻底剖析协程的实现原理
kotlin函数基础知识复习
再kotlin中函数是一等公民,有自己的类型
函数类型
fun foo(){} //类型为 () -> unit fun foo(p: int){} //类型为 (int) -> string class foo{ fun bar(p0: string,p1: long):any{} } //那么 bar 的类型为:foo.(string,long) -> any //foo就是bar的 receiver。也可以写成 (foo,string,long) ->any
函数引用
fun foo(){} //引用是 ::foo fun foo(p0: int): string //引用也是 ::foo
咋都一样?没办法,就这样规定的。使用的时候 只能靠编译器推断
val f: () -> unit = ::foo //编译器会推断出是fun foo(){} val g: (int) -> string = ::foo //推断为fun foo(p0: int): string
带receiver的写法
class foo{ fun bar(p0: string,p1: long):any{} }
val h: (foo,string,long) -> any = foo:bar
绑定receiver的函数引用:
val foo: foo = foo() val m: (string,long) -> any = foo:bar
额外知识点
val x: (foo,string,long) -> any = foo:bar val y: function3<foo,string,long,any> = x foo.(string,long) -> any = (foo,string,long) ->any = function3<foo,string,long,any>
函数作为参数传递
fun yy(p: (foo,string,long)->any){ p(foo(),"hello",3l)//直接p()就能调用 //p.invoke(foo(),"hello",3l) 也可以用invoke形式 }
lambda
就是匿名函数,它跟普通函数比是没有免费精选名字大全的,听起来好像是废话
//普通函数 fun func(){ println("hello"); } //去掉函数名 func,就成了匿名函数 fun(){ println("hello"); //可以赋值给一个变量 val func = fun(){ //匿名函数的类型 val func :()->unit = fun(){ //lambda表达式 val func={ print("hello"); //lambda类型 val func :()->string = { print("hello"); "hello" //如果是lambda中,最后一行被当作返回值,能省掉return。普通函数则不行 //带参数lambda val f1: (int)->unit = {p:int -> print(p); //可进一步简化为 val f1 = {p:int -> print(p); //当只有一个参数的时候,还可以写成 val f1: (int)->unit = { print(it);
关于函数的个人经验总结
函数跟匿名函数看起来没啥区别,但是反编译为java后还是能看出点差异
如果只是用普通的函数,那么他跟普通java 函数没啥区别。
比如 fun a()
就是对应java方法public void a(){}
但是如果通过函数引用(:: a)来用这个函数,那么他并不是直接调用fun a()
而是重新生成一个function0
挂起函数
suspend 修饰。
挂起函数中能调用任何函数。
非挂起函数只能调用非挂起函数。
换句话说,suspend函数只能在suspend函数中调用。
简单的挂起函数展示:
//com.example.studycoroutine.chapter.coroutinerun.kt suspend fun suspendfun(): int { return 1; }
挂起函数特殊在哪?
public static final object suspendfun(continuation completion) { return boxing.boxint(1); }
这下理解suspend为啥只能在suspend里面调用了吧?
想要让道貌岸然的suspend函数干活必须要先满足它!!!就是给它里面塞入一颗球。
然后他想调用其他的suspend函数,只需将球继续塞到其它的suspend方法里面。
普通函数里没这玩意啊,所以压根没法调用suspend函数。。。
读到这里,想必各位会有一些疑问:
- question1.这不是鸡生蛋生鸡的问题么?第一颗球是哪来的?
- question2.为啥编译后返回值也变了?
- question3.suspendfun 如果在协程体内被调用,那么他的球(completion)是谁?
标准库给我们提供的最原始工具
public fun <t> (suspend () -> t).startcoroutine(completion: continuation<t>) { createcoroutineunintercepted(completion).intercepted().resume(unit) } public fun <t> (suspend () -> t).createcoroutine(completion: continuation<t>): continuation<unit> = safecontinuation(createcoroutineunintercepted(completion).intercepted(), coroutine_suspended)
以一个最简单的方式启动一个协程。
demo-k1
fun main() { val b = suspend { val a = hello2() a } b.createcoroutine(mycompletioncontinuation()).resume(unit) } suspend fun hello2() = suspendcoroutine<int> { thread{ thread.sleep(1000) it.resume(10086) class mycontinuation() : continuation<int> { override val context: coroutinecontext = coroutinename("co-01") override fun resumewith(result: result<int>) { log("mycontinuation resumewith 结果 = ${result.getornull()}")
两个创建协程函数区别
startcoroutine 没有返回值 ,而createcoroutine返回一个continuation,不难看出是safecontinuation
好像看起来主要的区别就是startcoroutine直接调用resume(unit),所以不用包装成safecontinuation,而createcoroutine则返回一个safecontinuation,因为不知道将会在何时何处调用resume,必须保证resume只调用一次,所以包装为safecontinuation
safecontinuationd的作用是为了确保只有发生异步调用时才挂起
分析createcoroutineunintercepted
//kotlin.coroutines.intrinsics.coroutinesintrinsicsh.kt @sincekotlin("1.3") public expect fun <t> (suspend () -> t).createcoroutineunintercepted(completion: continuation<t>): continuation<unit>
先说结论
其实可以简单的理解为kotlin层面的原语,就是返回一个协程体。
开始分析
引用代码demo-k1首先b 是一个匿名函数,他肯定要被编译为一个functionx,同时它还被suspend修饰 所以它肯定跟普通匿名函数编译后不一样。
编译后的源码为
public static final void main() { function1 var0 = (function1)(new function1((continuation)null) { int label; @nullable public final object invokesuspend(@notnull object $result) { object var3 = intrinsicskt.getcoroutine_suspended(); object var10000; switch(this.label) { case 0: resultkt.throwonfailure($result); this.label = 1; var10000 = testsamplekt.hello2(this); if (var10000 == var3) { return var3; } break; case 1: var10000 = $result; default: throw new illegalstateexception("call to 'resume' before 'invoke' with coroutine"); } int a = ((number)var10000).intvalue(); return boxing.boxint(a); } @notnull public final continuation create(@notnull continuation completion) { intrinsics.checkparameterisnotnull(completion, "completion"); function1 var2 = new <anonymous constructor>(completion); return var2; public final object invoke(object var1) { return((<undefinedtype>)this.create((continuation)var1)).invokesuspend(unit.instance); }); boolean var1 = false; continuation var7 = continuationkt.createcoroutine(var0, (continuation)(newmycontinuation())); unit var8 = unit.instance; boolean var2 = false; companion var3 = result.companion; boolean var5 = false; object var6 = result.constructor-impl(var8); var7.resumewith(var6); }
我们可以看到先是 function1 var0 = new function1
创建了一个对象,此时跟协程没关系,这步只是编译器层面的匿名函数语法优化
如果直接
fun main() { suspend { val a = hello2() a }.createcoroutine(mycontinuation()).resume(unit) }
也是一样会创建function1 var0 = new function1
解答question1
继续调用createcoroutine
再继续createcoroutineunintercepted ,找到在jvm平台的实现
//kotlin.coroutines.intrinsics.intrinsicsjvm.class @sincekotlin("1.3") public actual fun <t> (suspend () -> t).createcoroutineunintercepted( completion: continuation<t> ): continuation<unit> { //probecompletion还是我们传入completion对象,在我们的demo就是mycoroutine val probecompletion = probecoroutinecreated(completion)//probecoroutinecreated方法点进去看了,好像是debug用的.我的理解是这样的 //this就是这个suspend lambda。在demo中就是mycoroutinefun return if (this is basecontinuationimpl) create(probecompletion) else //else分支在我们demo中不会走到 //当 [createcoroutineunintercepted] 遇到不继承 basecontinuationimpl 的挂起 lambda 时,将使用此函数。 createcoroutinefromsuspendfunction(probecompletion) { (this as function1<continuation<t>, any?>).invoke(it) } }
@notnull public final continuation create(@notnull continuation completion) { intrinsics.checknotnullparameter(completion, "completion"); function1 var2 = new <anonymous constructor>(completion); return var2; }
把completion传入,并创建一个新的function1,作为continuation返回,这就是创建出来的协程体对象,协程的工作核心就是它内部的状态机,invokesuspend函数
调用 create
@notnull public final continuation create(@notnull continuation completion) { intrinsics.checknotnullparameter(completion, "completion"); function1 var2 = new <anonymous constructor>(completion); return var2; }
把completion传入,并创建一个新的function1,作为continuation返回,这就是创建出来的协程体对象,协程的工作核心就是它内部的状态机,invokesuspend函数
补充—相关类继承关系
解答question2&3
已知协程启动会调用协程体的resume,该调用最终会来到basecontinuationimpl::resumewith
internal abstract class basecontinuationimpl{ fun resumewith(result: result<any?>) { // this loop unrolls recursion in current.resumewith(param) to make saner and shorter stack traces on resume var current = this var param = result while (true) { with(current) { val completion = completion!! // fail fast when trying to resume continuation without completion val outcome: result<any?> = try { val outcome = invokesuspend(param)//调用状态机 if (outcome === coroutine_suspended) return result.success(outcome) } catch (exception: throwable) { result.failure(exception) } releaseintercepted() // this state machine instance is terminating if (completion is basecontinuationimpl) { // unrolling recursion via loop current = completion param = outcome } else { //最终走到这里,这个completion就是被塞的第一颗球。 completion.resumewith(outcome) return } } } } }
状态机代码截取
public final object invokesuspend(@notnull object $result) { object var3 = intrinsicskt.getcoroutine_suspended(); object var10000; switch(this.label) { case 0://第一次进来 label = 0 resultkt.throwonfailure($result); // label改成1了,意味着下一次被恢复的时候会走case 1,这就是所谓的【状态流转】 this.label = 1; //全体目光向我看齐,我宣布个事:this is 协程体对象。 var10000 = testsamplekt.hello2(this); if (var10000 == var3) { return var3; } break; case 1: resultkt.throwonfailure($result); var10000 = $result; break; default: throw new illegalstateexception("call to 'resume' before 'invoke' with coroutine"); } int a = ((number)var10000).intvalue(); return boxing.boxint(a); }
question3答案出来了,传进去的是create创建的那个continuation
最后再来聊聊question2,从上面的代码已经很清楚的告诉我们为啥挂起函数反编译后的返回值变为object了。
以hello2为例子,hello2能返回代表挂起的白板,也能返回result。如果返回白板,状态机return,协程挂起。如果返回result,那么hello2执行完毕,是一个没有挂起的挂起函数,通常编译器也会提醒 suspend 修饰词无意义。所以这就是设计需要,没有啥因为所以。
最后,除了直接返回结果的情况,挂起函数一定会以resume结尾,要么返回result,要么返回异常。代表这个挂起函数返回了。
调用resume意义在于重新回调basecontinuationimpl的resumewith,进而唤醒状态机,继续执行协程体的代码。
换句话说,我们自定义的suspend函数,一定要利用suspendcoroutine 获得续体,即状态机对象,否则无法实现真正的挂起与resume。
suspendcoroutine
我们可以不用suspendcoroutine,用更直接的suspendcoroutineuninterceptedorreturn也能实现,不过这种方式要手动返回白板。不过一定要小心,要在合理的情况下返回或者不返回,不然会产生很多意想不到的结果
suspend fun mysuspendone() = suspendcoroutineuninterceptedorreturn<string> { continuation -> thread { timeunit.seconds.sleep(1) continuation.resume("hello world") } //因为我们这个函数没有返回正确结果,所以必须返回一个挂起标识,否则basecontinuationimpl会认为完成了任务。 // 并且我们的线程又在运行没有取消,这将很多意想不到的结果 kotlin.coroutines.intrinsics.coroutine_suspended }
而suspendcoroutine则没有这个隐患
suspend fun mysafesuspendone() = suspendcoroutine<string> { continuation -> thread { timeunit.seconds.sleep(1) continuation.resume("hello world") } //suspendcoroutine函数很聪明的帮我们判断返回结果如果不是想要的对象,自动返 kotlin.coroutines.intrinsics.coroutine_suspended }
public suspend inline fun <t> suspendcoroutine(crossinline block: (continuation<t>) -> unit): t = suspendcoroutineuninterceptedorreturn { c: continuation<t> -> //封装一个代理continuation对象 val safe = safecontinuation(c.intercepted()) block(safe) //根据block返回结果判断要不要返回coroutine_suspended safe.getorthrow() }
safecontinuation的奥秘
//调用单参数的这个构造方法 internal actual constructor(delegate: continuation<t>) : this(delegate, undecided) @volatile private var result: any? = initialresult //undecided赋值给 result //java原子属性更新器那一套东西 private companion object { @suppress("unchecked_cast") @jvmstatic private val result = atomicreferencefieldupdater.newupdater<safecontinuation<*>, any?>( safecontinuation::class.java, any::class.java as class<any?>, "result" ) } internal actual fun getorthrow(): any? { var result = this.result // atomic read if (result === undecided) { //如果undecided,那么就把result设置为coroutine_suspended if (result.compareandset(this, undecided, coroutine_suspended)) returncoroutine_suspended result = this.result // reread volatile var return when { result === resumed -> coroutine_suspended // already called continuation, indicate coroutine_suspended upstream result is result.failure -> throw result.exception else -> result // either coroutine_suspended or data <-这里返回白板 } public actual override fun resumewith(result: result<t>) { while (true) { // lock-free loop val cur = this.result // atomic read。不理解这里的官方注释为啥叫做原子读。我觉得 volatile只能保证可见性。 when { //这里如果是undecided 就把 结果附上去。 cur === undecided -> if (result.compareandset(this, undecided, result.value)) return //如果是挂起状态,就通过resumewith回调状态机 cur === coroutine_suspended -> if (result.compareandset(this, coroutine_suspended, resumed)){ delegate.resumewith(result) return } else -> throw illegalstateexception("already resumed") } }
val safe = safecontinuation(c.intercepted()) block(safe) safe.getorthrow()
先回顾一下什么叫真正的挂起,就是getorthrow返回了“白板”,那么什么时候getorthrow能返回白板?答案就是result被初始化后值没被修改过。那么也就是说resumewith没有被执行过,即:block(safe)这句代码,block这个被传进来的函数,执行过程中没有调用safe的resumewith。原理就是这么简单,cas代码保证关键逻辑的原子性与并发安全
继续以demo-k1为例子,这里假设hello2运行在一条新的子线程,否则仍然是没有挂起。
{ thread{ thread.sleep(1000) it.resume(10086) } }
总结
最后,可以说开启一个协程,就是利用编译器生成一个状态机对象,帮我们把回调代码拍扁,成为同步代码。
到此这篇关于android中的coroutine协程原理详解的文章就介绍到这了,更多相关android coroutine原理内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/1069651.html