当前位置:网站首页>Kotlin coprocess analysis (III) -- understanding the context of coprocess
Kotlin coprocess analysis (III) -- understanding the context of coprocess
2022-07-24 07:58:00 【catzifeng】
List of articles
Collaboration context ——CoroutineContext It is a very important link in the coordination process , You can say that , Almost the business capability of the whole cooperation process is completed by it .
Tell the truth , This source code is not very good-looking , It is also difficult to explain in detail , If you have any doubts in the next reading , Let's talk about learning .
One 、 Brief introduction CoroutineContext
The coroutine context is actually a aggregate , There can be many business-related Context, for example :Job, Objects used to control collaborative tasks ;Dispatcher, The object used to schedule the process thread .
In any process , Even including suspended functions , Can be obtained coroutineContext, adopt get() Method to get specific Context To do business .
Two 、CoroutineContext Data structure of
Understanding its data structure is a very important link , In this way, you can understand some of its normal operation , For example, it has appeared before :context = SupervisorJob() + Dispatchers.Main What's going on? ,coroutineContext[Job] What has this done ?
As the first section says , CoroutineContext It's a aggregate , So what kind of set is this ? Let's take a look at his notes first :
Persistent context for the coroutine. It is an indexed set of Element instances.
An indexed set is a mix between a set and a map. Every element in this set has a unique Key.
translate : This is an element called Element Set , A between set and map Set between , Any one of them element There is a unique Key.
Since this is a set , We read his directly “put” and get Method :
1.“put”( Learn more CoroutineContext Data structure of )
CoroutineContext Of “put” The method is not direct “put”,CoroutineContext Itself is a collection , In the realization of “put” when , It uses a trick —— rewrite “+ Number ” The operator :
1). This function is adding new CoroutineContext after , Will return a containing all contexts CoroutineContext( Here we need to understand it , It's similar to a linked list / Nodule of tree ).
2). First judge what you want to join context Is it EmptyCoroutineContext, If it's empty CoroutineContext, Go directly back to the current CoroutineContext.
3). If you join context No EmptyCoroutineContext, So call CoroutineContext.fold() Conduct “ Fold ” Join in .
4). Look at all fold() Implementation of function , All in all 3 It's about :EmptyCoroutineContext、Element and CombinedContext, Come here , We need to simply look at the source code of these three types of related functions ( Don't look too much , Just look at fold function ).
Let's analyze... One by one :
1.1 EmptyCoroutineContext
public override fun <R> fold(initial: R, operation: (R, Element) -> R): R = initial
This is the best understood ,EmptyCoroutineContext.fold( arbitrarily Context) = arbitrarily Context
namely :EmptyCoroutineContext + arbitrarily Context = arbitrarily Context.
1.2 Element
public override fun <R> fold(initial: R, operation: (R, Element) -> R): R =
operation(initial, this)
This is easy to understand , Put... Directly By foldConext and own Context Put in operation in , see operation The operation of .
namely :
Element + arbitrarily Context = arbitrarily Context.fold(Element) =
{
acc( Oneself Context),element( The goal is Context) ->
return After the operation CoroutineContext
}
1.2 CombinedContext
About CombinedContext Let's not look at it first fold() function , Look at the name first : It means to combine ( Two in one ) Of Context, It's kind of interesting , Let's first look at its constructor :
internal class CombinedContext(
private val left: CoroutineContext,
private val element: Element
) : CoroutineContext, Serializable
Read notes , It says this is a left linked list structure , Contains left Of CoroutineContext Elements , And your own Element(Element Inherited from CoroutineContext), Seeing here is actually almost a further understanding CoroutineContext Data structure of .
About it fold() function , Let's not watch it yet .
Now let's assume a scenario : arbitrarily Context( Inherited from Element, Hereinafter referred to as itself Context) + Any other Context( Inherited from Element, Hereinafter referred to as goals Context) What kind of process will it be ?
Combine the source code with the above 1.2 Element What is the result of addition? Let's analyze it together , Then I'll go operation What's in it :
First look at operation What are the two parameters of ,acc == Oneself Context,element == The goal is Context
step 1: Oneself Context Remove The goal is Context, And return the removed CoroutineContext
step 2: Judge the removed CoroutineContext Is it EmptyCoroutineContext, If EmptyCoroutineContext, Then go straight back The goal is Context, What does that mean ?
Assume yourself Context And the target Context equal (Key equal ), Then the removed CoroutineContext == EmptyCoroutineContext, So there is no need to add , Return directly to the target Context.
Assume yourself Contxt And the target Context It's not equal , Then come to the next step
step 3: First look at the notes above , This operation is to make a person named ContinuationInterceptor Of Context Can always be in the last position , Easy and fast access ,
Here we assume the goal Context And myself Context None of them contain ContinuationInterceptor, that interceptor == null,
Finally, go straight back to : CombinedContext(removed- Remove target Context After that Context, element- The goal is Context).
Guys , Read the source code here , You should already be very clear CoroutineContext Data structure of , Here I'll draw a picture , More clearly ( a key ):
2.get
CoroutineContext rewrite “get The operator ”:
public operator fun <E : Element> get(key: Key<E>): E?
There are also several implementations , Namely Element、CombinedContext、EmptyCoroutineContext and ContinuationInterceptor, About ContinuationInterceptor I won't give you too much introduction here , This sum CoroutineContext Is independent of the data structure , Specific CoroutineContext Business capabilities .
1.1 EmptyCoroutineContext
Look at the source code directly :
public override fun <E : Element> get(key: Key<E>): E? = null
Because it is empty CoroutineContext, So go straight back null.
1.2 Element
Look at the source code directly :
public override operator fun <E : Element> get(key: Key<E>): E? =
if (this.key == key) this as E else null
As the element itself , So direct judgment key Whether it is equal or not , If equal, return directly to itself CoroutineContext.
1.3 CombinedContext
As an important guest , Its source code is still very important :
override fun <E : Element> get(key: Key<E>): E? {
var cur = this
while (true) {
cur.element[key]?.let {
return it }
val next = cur.left
if (next is CombinedContext) {
cur = next
} else {
return next[key]
}
}
}
I think look at the source code , combining The picture drawn above It should be easy to understand its search order .
边栏推荐
- Image feature SIFT (scale invariant feature transform)
- What is the NFT concept.. Fully understand NFT market, technology and cases
- Digital twin demonstration project -- Talking about simple pendulum (4) IOT exploration
- Anaconda install pytorch
- [target detection] IOU (intersection and combination ratio)
- 学习笔记总结篇(一)
- abstract class
- 13. Unity2d horizontal version of two-way platform that can move up, down, left and right (two-way walking + movable + independent judgment) + random platform generation
- Semantic slam: Probabilistic Data Association for semantic slam
- Image feature Harris corner detection
猜你喜欢

Facing Tencent (actual combat) - Test Development - detailed explanation of interns (face experience)

Debug No1 summarizes common solutions to bugs

Do you want to have a robot that can make cartoon avatars in three steps?

Use JMeter to analyze and test the lottery probability of the lottery interface

NFT是什么?一篇文章搞懂NFT的概念

【线性代数】深入理解矩阵乘法、对称矩阵、正定矩阵

Kubernetes: (I) basic concepts

*Project recurrence * project implementation of thesis based on contextbasedemotionrecognitionusingematicdataset

学习笔记总结篇(一)

Super simple countdown code writing
随机推荐
Selenium basic knowledge debugging method
Opencv project - credit card recognition (learning record)
Tools for data visualization
Perceptron and multilayer neural network, back propagation and computational graph
Learning dynamic Siamese network for visual object tracking full text translation
Continuous learning, lifelong learning, episodic memory, memory module paper summary -- gradient episodic memory promotes continuous learning
Why is knowledge base important? This is the best answer I've ever heard
Introduction to webmethods
Telecom Customer Churn Prediction challenge baseline [AI competition]
Digital twin demonstration project -- Talking about simple pendulum (2) vision exploration and application scenarios
Digital twin demonstration project -- Talking about simple pendulum (4) IOT exploration
CNN-VINS
Semantic slam: Probabilistic Data Association for semantic slam
Case practice - panoramic image mosaic: feature matching method
A simple mobile terminal todo
Debug No3 multi texture overlay
HCIP第七天
【线性代数】深入理解矩阵乘法、对称矩阵、正定矩阵
One click Copy and import of web interface data into postman
Robot operation continuous learning thesis (1) original text reading and Translation -- primitive generation strategy learning without catastrophic forgetting in robot operation