协程(22) Channel原理解析_xvpp002(1),头条面试一般几轮

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新HarmonyOS鸿蒙全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img

img
img
htt

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip204888 (备注鸿蒙)
img

正文

internal abstract class AbstractSendChannel(
@JvmField protected val onUndeliveredElement: OnUndeliveredElement?
) : SendChannel {
protected val queue = LockFreeLinkedListHead()

可以发现这是一个queue,即队列,同时它还是一个线程安全的队列,从LockFreeLinkedList就可以看出,它是一个没有使用锁LockLinkedList

//Head只是一个哨兵节点
public actual open class LockFreeLinkedListHead : LockFreeLinkedListNode()

//线程安全的双向链表
public actual open class LockFreeLinkedListNode {
private val _next = atomic(this) // Node | Removed | OpDescriptor
private val _prev = atomic(this) // Node to the left (cannot be marked as removed)
private val _removedRef = atomic<Removed?>(null)

关于这个数据结构,这里不做过多分析,等后面有时间可以专门研究一下,这个线程安全的数据结构,有如下特点:

  • 它是一个双向链表结构,按理说双向链表的插入可以从头或者尾都是可以的,但是在这里,定义了插入只能是尾部,即右边;而获取元素,只能从头部,即左边。
  • 它有一个哨兵节点,哨兵节点是不存储数据的,它的next节点是数据节点的头节点,它的pre节点是数据节点的尾节点,当数据节点为空时,依旧有哨兵节点。
  • 该数据结构中,保存数据使用了atomic,即CAS技术,这样可以保证这个链表的操作是线程安全的。

到这里,我们已经知道了在AbstractChannel中存在一个线程安全的双向队列,至于节点保存的数据是什么,后面待会再分析。

send流程分析

我们以文章开始的测试代码为例,当调用send(0)时,实现方法就是AbstractChannel中:

//发送数据
public final override suspend fun send(element: E) {
// fast path – try offer non-blocking
if (offerInternal(element) === OFFER_SUCCESS) return
// slow-path does suspend or throws exception
//挂起函数
return sendSuspend(element)
}

在该方法中,有2个分支,当offerInternal方法返回结果为OFFER_SUCCESS时,就直接return,否则调用挂起发送函数sendSuspend
看到这个offerInternal(element)方法,我相信肯定会立马和前面所说的队列结合起来,因为offer这个单词就属于队列中的一种术语,表示增加的意思,和add一样,但是返回值不一样。
所以我们可以大致猜出该方法作用:把element添加到队列中,如果添加成功,则直接返回,否则则挂起。我们来看看offerInternal()方法:

//尝试往buffer中增加元素,或者给消费者增加元素
protected open fun offerInternal(element: E): Any {
while (true) {
val receive = takeFirstReceiveOrPeekClosed() ?: return OFFER_FAILED
val token = receive.tryResumeReceive(element, null)
if (token != null) {
assert { token === RESUME_TOKEN }
receive.completeResumeReceive(element)
return receive.offerResult
}
}
}

该方法会往buffer中或者消费者增加数据,会成功返回数据,或者增加失败。
根据前面我们设置的是默认Channel,是没有buffer的,且没有调用receive,即也没有消费者,所以这里会直接返回OFFER_FAILED
所以我们执行流程跳转到sendSuspend:

//send的挂起函数
private suspend fun sendSuspend(element: E): Unit = suspendCancellableCoroutineReusable sc@ { cont ->
loop@ while (true) {
//buffer是否已满,本例中,是满的
if (isFullImpl) {
//封装为SendElement
val send = if (onUndeliveredElement == null)
SendElement(element, cont) else
SendElementWithUndeliveredHandler(element, cont, onUndeliveredElement)
//入队
val enqueueResult = enqueueSend(send)
when {
enqueueResult == null -> { // enqueued successfully
cont.removeOnCancellation(send)
return@sc
}
enqueueResult is Closed<> -> {
cont.helpCloseAndResumeWithSendException(element, enqueueResult)
return@sc
}
enqueueResult === ENQUEUE_FAILED -> {} // try to offer instead
enqueueResult is Receive<
> -> {} // try to offer instead
else -> error(“enqueueSend returned $enqueueResult”)
}
}

}
}

这就是send的挂起函数方式实现,分析:

  • 这里使用suspendCancellableCoroutineReusable挂起函数,和我们之前所说的suspendCancellableCoroutine{}高阶函数一样,属于能接触到的最底层实现挂起函数的方法了,其中cont就是用来向挂起函数外部传递数据。
  • 在实现体中,首先判断isFullImpl即是否满了,由于本例测试代码的Channel是没有容量的,所以是满的。
  • 然后把elementcont封装为SendElement对象,这里的element就是我们之前所发送的0, 而continuation则代表后续的操作。
    这个SendElement类定义如下:

//发送元素
internal open class SendElement(
override val pollResult: E,
@JvmField val cont: CancellableContinuation
) : Send() {
override fun tryResumeSend(otherOp: PrepareOp?): Symbol? {
val token = cont.tryResume(Unit, otherOp?.desc) ?: return null
assert { token === RESUME_TOKEN } // the only other possible result
// We can call finishPrepare only after successful tryResume, so that only good affected node is saved
otherOp?.finishPrepare() // finish preparations
return RESUME_TOKEN
}

override fun completeResumeSend() = cont.completeResume(RESUME_TOKEN)
override fun resumeSendClosed(closed: Closed<*>) = cont.resumeWithException(closed.sendException)
override fun toString(): String = “ c l a s s S i m p l e N a m e @ classSimpleName@ classSimpleName@hexAddress($pollResult)”
}

从这里我们可以看出,这个Element就是把要发送的元素和Continuation给包装起来,而前面所说的双向链表中的元素也就是这种Element

  • 接着调用enqueueSend方法,把上面这个Element入队,根据该方法的返回值定义,这里会返回null,表示插入成功。
  • 然后当入队成功时,会调用下面代码块:

enqueueResult == null -> { // enqueued successfully
cont.removeOnCancellation(send)
return@sc
}

这里先是给cont设置了一个监听:

//给CancellableContinuation设置监听
internal fun CancellableContinuation<*>.removeOnCancellation(node: LockFreeLinkedListNode) =
invokeOnCancellation(handler = RemoveOnCancel(node).asHandler)

//当Continuation被取消时,节点自动从队列中remove掉
private class RemoveOnCancel(private val node: LockFreeLinkedListNode) : BeforeResumeCancelHandler() {
override fun invoke(cause: Throwable?) { node.remove() }
override fun toString() = “RemoveOnCancel[$node]”
}

这个监听作用就是当Continuation执行完成或者被取消时,该节点可以从双向队列中被移除。
然后就是return@sc,这里是不是很疑惑呢?在以前我们实现挂起函数时,都是通过continuationresume方法来传递挂起函数的值,同时也是恢复的步骤,这里居然没有恢复。那这个挂起函数该什么时候恢复呢?Channel是如何来恢复的呢?

receive流程分析

我们接着分析,其实就是当调用receive()的时候。
receive()的实现,根据前面分析就是在AbstractChannel中:

//接收方法的实现
public final override suspend fun receive(): E {
// fast path – try poll non-blocking
val result = pollInternal()
@Suppress(“UNCHECKED_CAST”)
if (result !== POLL_FAILED && result !is Closed<*>) return result as E
// slow-path does suspend
return receiveSuspend(RECEIVE_THROWS_ON_CLOSE)
}

这里同样是类似的逻辑,首先是pollInternal方法,这里的poll同样和offer一样,属于队列的术语,有轮询的意思,和remove类似的意思,所以该方法就是从队列中取出元素,我们来看看实现:

//尝试从buffer或者发送端中取出元素
protected open fun pollInternal(): Any? {
while (true) {
//取出SendElement
val send = takeFirstSendOrPeekClosed() ?: return POLL_FAILED
//注释1
val token = send.tryResumeSend(null)
if (token != null) {
assert { token === RESUME_TOKEN }
//注释2
send.completeResumeSend()
return send.pollResult
}
// too late, already cancelled, but we removed it from the queue and need to notify on undelivered element
send.undeliveredElement()
}
}

根据前面我们send的流程,这时可以成功取出我们之前入队的SendElement对象,然后调用注释2处的send.completeResumeSend()方法:

override fun completeResumeSend() = cont.completeResume(RESUME_TOKEN)

这里会调用continuationcompleteResume方法,这里就需要结合前面文章所说的原理了,其实这个continuation就是状态机,它会回调CancellableContinuationImpl中的completeResume:

override fun completeResume(token: Any) {
assert { token === RESUME_TOKEN }
dispatchResume(resumeMode)
}

而该类的继承关系:

internal open class CancellableContinuationImpl(
final override val delegate: Continuation,
resumeMode: Int
) : DispatchedTask(resumeMode), CancellableContinuation, CoroutineStackFrame

这里相关的类,我们在线程调度那篇文章中有所提及,这里的dispatchResume:

private fun dispatchResume(mode: Int) {
if (tryResume()) return // completed before getResult invocation – bail out
// otherwise, getResult has already commenced, i.e. completed later or in other thread
dispatch(mode)
}

internal fun DispatchedTask.dispatch(mode: Int) {

if (dispatcher.isDispatchNeeded(context)) {
dispatcher.dispatch(context, this)
}

}

这里最终会调用dispatcher.dispatch()方法,而这个我们在之前调度器文章说过,这个最后会在Java线程池上执行,从而开始状态机。
既然该状态机恢复了,也就是前面send流程中的挂起也恢复了。
send挂起函数恢复后,再通过

return send.pollResult

就可以获取我们之前发送的值0了。

同样的,当pollInternal方法中,无法pollSendElement,则会调用receiveSuspend挂起方法:

private suspend fun receiveSuspend(receiveMode: Int): R = suspendCancellableCoroutineReusable sc@ { cont ->
val receive = if (onUndeliveredElement == null)
ReceiveElement(cont as CancellableContinuation<Any?>, receiveMode) else
ReceiveElementWithUndeliveredHandler(cont as CancellableContinuation<Any?>, receiveMode, onUndeliveredElement)
while (true) {
if (enqueueReceive(receive)) {
removeReceiveOnCancel(cont, receive)
return@sc
}
// hm… something is not right. try to poll
val result = pollInternal()
if (result is Closed<*>) {
receive.resumeReceiveClosed(result)
return@sc
}
if (result !== POLL_FAILED) {
cont.resume(receive.resumeValue(result as E), receive.resumeOnCancellationFun(result as E))
return@sc
}
}
}

send类似,这里也会封装为ReceiveElement,同时入队到队列中,等待着send方法来恢复这个协程。

"热"的探究

分析完默认的Channel的发送和接收,我们来探究一下为什么Channel是热的。
这里所说的热是因为Channel会在不管有没有接收者的情况下,都会执行发送端的操作,当策略为Suspend时,它会一直持续到管道容量满。

这里我们还是拿之前文章的例子:

fun main() = runBlocking {
//创建管道 val channel = produce(capacity = 10) {
(1 … 3).forEach {
send(it)
logX(“Send $it”)
}
}
logX(“end”) }

这里虽然没有调用receive方法,即没有消费者,send依旧会执行,也就是"热"的。

根据前面所说的Channel()顶层函数源码,这里容量为10,策略不变,最终会创建出ArrayChannel实例。
该类定义:

internal open class ArrayChannel(
/**

  • Buffer capacity.
    */
    private val capacity: Int,
    private val onBufferOverflow: BufferOverflow,
    onUndeliveredElement: OnUndeliveredElement?
    ) : AbstractChannel(onUndeliveredElement)

这里同样是AbstractChannel的子类,所以send方法还是依旧:

public final override suspend fun send(element: E) {
// fast path – try offer non-blocking
if (offerInternal(element) === OFFER_SUCCESS) return
// slow-path does suspend or throws exception
return sendSuspend(element)
}

还是先尝试往队列中offer数据,当无法offer时,执行挂起;但是这里的offerInternal方法在ArrayChannel中被重写了:

//ArrayChannel中的方法
protected override fun offerInternal(element: E): Any {
//接收者

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

还是先尝试往队列中offer数据,当无法offer时,执行挂起;但是这里的offerInternal方法在ArrayChannel中被重写了:

//ArrayChannel中的方法
protected override fun offerInternal(element: E): Any {
//接收者

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注鸿蒙)
[外链图片转存中…(img-5uWgIMVt-1713382943373)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 21
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值