当前位置:网站首页>Talk about how the kotlin process started?
Talk about how the kotlin process started?
2022-06-30 09:01:00 【Byte station】
1. Preface
This paper mainly introduces the starting principle of synergetic process , If you don't have actual experience in cooperative process or Debug Source code of cooperative process , It may seem like a bit of a struggle , But if you have the opportunity to learn the source code of the collaborative process in the future , Then this article may be of some help to you . This article mainly explains the process of starting the collaboration process , For simplicity , Other important collaborative process knowledge points involved in this process may only be briefly mentioned , This article will not go into details , They will be written separately in the future when they are free .
2. A simple example
First Let's take a simple example , Open a coroutine in the main thread , Print “Hello Coroutines”. Use this simple example to explain how the collaboration process is started .
next We will startCoroutines Method is decompiled into Java file 
We see Kotlin In code Lambda The expression becomes Java Medium Function2 object , And its corresponding concrete class is SuspendLambda.
We notice that it implements three methods :
- Object invokeSuspend(Object var1)
- Continuation create(Object value,Continuation completion)
- Object invoke(Object var1,Object var2)



If you look carefully, you will find ,invokeSuspend and create Method defined in BaseContinuationImpl in ,invoke Method definition Function2 in . and SuspendLambda Inherited ContinuationImpl At the same time, it realized SuspendFunction Interface .
stay Kotlin in , Methods are also objects , The class corresponding to the method of a parameter is Function1, By analogy, the two parameter methods correspond to Function2.
Writing at this point , There are a lot of new things ,suspend、Continuation、CoroutineScope、CoroutineContext, But this article will not cover , Next, let's look at the process of starting the collaboration .
3. The boot process
3.1 CoroutineScope.launch

The function of this method is as follows :
- Create a new... For the new collaboration CoroutineContext
- this paper Case establish StandaloneCoroutine
- call coroutine.start Method to start the process

The function of this method is as follows :
- call initParentJob Method , With the father Job Establishing correlation , When calling cancel Method or sub Job When there is abnormal , Cancellation or exception events can be propagated upward ( This article ignores , It's good to have a simple understanding )
- call start(block, receiver, this), This method is super confusing , What it really calls is CoroutineStart Of invoke Method .
3.2 CoroutineStart.invoke

In this case DEFAULT Branch
3.3 (suspend->T).startCoroutineCancellable

And finally through suspend Methodical startCoroutineCancellable Method to start the process , This article corresponds to lambda, As we mentioned earlier, it corresponds to SuspendLambda
{
println("Hello Coroutines")
}
This method contains several important method calls :
- (suspend R.()->T).createCoroutineUnintercepted
- Continuation.intercepted()
- Continuation.resumeCancellableWith
3.4 (suspend R.() -> T).createCoroutineUnintercepted

Current this Is the closure of the startup process , Previously, we decompile startCoroutines Method , It is found that closures implement create Method , What is called here is generated after decompilation create Method

Parameters completion The corresponding is the co process StandaloneCoroutine, Generated here Function2 Object is also SuspendLambda object
3.5 Continuation.intercepted()

The main function of this method is to generate DispatchedContinuation. It consists of CoroutineDispatcher and Continuation Two parts .Dispatcher Decided to Continuation In which thread , This article is on the main thread
3.6 Continuation.resumeCancellableWith

3.7 MainScope

Dispatchers.Main In the end by the kotlinx.coroutines.android.AndroidDispatcherFactory establish
3.8 AndroidDispatcherFactory

Finally through Handler.post Method to DispatchedContinuation Put into the main thread message queue
3.9 DispatchedTask.run
Android Main thread scheduling , Will eventually be called to DispatchedTask.run In the method , adopt continuation.resume Method to execute the coroutine body .
3.10 BaseContinuationImpl.resumeWith
ContinuationImpl.kt
This method loops through Continuation Of invokeSuspend Method , Until now completion Is that the coroutine itself will jump out of the loop .
Actually print “Hello Coroutines”
3.11 AbstractCoroutine.resumeWith
The coordination process is completed 
Indicates that the execution of the collaboration process ends , It may need to wait for the subprocess to end , After that, you need to inform the parent collaboration process
4. summary
There are too many pre knowledge points in the coordination process , An article cannot explain clearly , Questions can be raised in the comment area . This article mainly explains Dispatchers.Main The process of starting a collaboration .Dispatchers.Default The process of starting the process is completely different from it .
Remember to pay attention to “ Byte station ” The official account ~
边栏推荐
- Occasionally, Flink data is overstocked, resulting in checkpoint failure
- 2021-05-06
- Resnet50+fpn for mmdet line by line code interpretation
- Anchorgenerator for mmdet line by line interpretation
- [untitled]
- How can I get the discount for opening a securities account? Is online account opening safe?
- Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
- Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)
- Codeworks 5 questions per day (1700 for each) - the third day
- How to format an UTC date to use the Z (Zulu) zone designator in php?
猜你喜欢

Rew acoustic test (II): offline test

2021-04-29

Mmdet line by line deltaxywhbboxcoder

Redis design and Implementation (I) | data structure & object

el-input 限制只能输数字

Qt连接神通数据库

Codeworks 5 questions per day (1700 for each) - the third day

Circuit analysis of current probe

Build a docker image of Henkel database from 0

Metasploit practice - SSH brute force cracking process
随机推荐
Esp32 things (I): Preface
Does the oscilloscope probe affect the measurement of capacitive load?
自制GIF动态图-gifcam
Circuit analysis of current probe
Self made GIF dynamic graph -gifcam
Vite project require syntax compatibility problem solving require is not defined
Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
[paid promotion] collection of frequently asked questions, FAQ of recommended list
Metasploit practice - SSH brute force cracking process
El input limit can only input numbers
Rew acoustic test (I): microphone calibration
TiDB v6.0.0 (DMR) :缓存表初试丨TiDB Book Rush
Esp32 (IX): OTA function of function development
Qt通过Url下载文件
Axure make menu bar effect
Esp32 (7): I2S and I2C drivers for function development
Sort (simple description)
JVM tuning related commands and explanations
PHP API to obtain QR code and combine to generate pictures
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)