In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to understand Kotlin Cooperative Program". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand Kotlin Cooperative Program".
The emergence of the cooperative process
Let's first talk about the history of Xiecheng, and how it got so miserable. After all, a miserable life needs an explanation.
Collaborative program was first born in 1958 and has been used in assembly language (more than 60 years ago). A complete definition of it was published in 1963. Collaborative program is a program component that implements collaborative multitasking through the resumption and pause of code execution.
At the same time, the emergence of threads was later, and with the advent of the operating system, threads were proposed around 1967. As the smallest execution component scheduled by the operating system, threads are mainly used to achieve preemptive multitasking.
Since everyone is multitasking, no one can be much better than the other, and since Xiecheng is still a few years earlier, it is theoretically possible to occupy a core position in the programming language through its own efforts.
However, the development of this cooperation process, ah, on the one hand, we have to rely on self-struggle, on the other hand, we should also consider the historical process. In the 1970s, 1980s and 1990s, computers were crazily evolving towards miniaturization and personalization. Computers relied heavily on the operating system to provide user interaction and squeeze the maximum performance of CPU, but how did the operating system squeeze computer performance? Rely on multithreading. After the operating system follows the popularity of personal computers, programming languages naturally begin to rely on the interface provided by the operating system to control computers. Threading has become an important concept that almost all programming languages can not skip, and continues to this day.
At this point, you may want to ask, everyone is multitasking, why threads can improve the resource utilization of cpu, but not collaboration?
Of course, there are many other reasons that can be explained, but the most essential reason is that there is a significant difference between co-programming and threading, so let's go back to collaborative multitasking and preemptive multitasking. And whether the two tasks are the same concept?
Collaborative multitasking:
The picture above is part of a sushi production process. We can regard the transfer turntable and machine grip in the picture as two tasks, working together to complete the food production. This is collaborative multitasking. Collaborative multitasking requires mutual familiarity between tasks in order to achieve collaboration.
Preemptive multitasking:
In the scene of feeding goldfish, as soon as a handful of feed goes down, all the goldfish are immediately gathered around and emptied, where each goldfish is equivalent to a task thread, which is preemptive multitasking. There is no need for understanding and cooperation between preemptive multitasking (threads), only competition.
The above two pictures vividly show the difference between collaborative multitasking (collaborative programming) and preemptive multitasking (multithreading). We can find that the collaborative process is more suitable for those task components that are familiar with each other to accomplish some work through close cooperation, and the "task" in collaborative multitasking is a subprogram (which can be called a function). Tasks in preemptive multitasking refer to components or code that can preempt resources (that is, threads), and multitasking here is multithreading. Therefore, co-program and thread are two very different concepts, and their capabilities are different, and this ability of threads meets the needs of that era. Self-struggle + historical process is the main reason for the success of threads.
Of course, on the other hand, because the collaborative program is based on a concept at the programming language level, it does not have a uniformly defined interface, so the effect of implementation in different languages is different, which will cause great trouble to developers and is not conducive to its promotion. On the other hand, threads, through the unified interface of the operating system, define roughly the same way of using threads, which ensures that different programming languages use threads roughly the same.
At this point, let's summarize the reasons for the early development of Xiancheng:
Xiecheng does not represent the development requirements of advanced productive forces, the direction of advanced culture, and the fundamental interests of the overwhelming majority of developers [manual dog head].
The actual performance of collaborative program is different in different programming languages, which is not conducive to the understanding and use of developers.
The above two points are the reasons why Xiecheng has been lukewarm for decades. We also see that although they all seem to be multitasking, there is actually not much overlap between the co-program and the thread.
Salted fish turns over
Although collaborative multi-tasking components such as collaborative process can not improve the efficiency of program execution, it does not seem to have a wide application prospect, but this collaborative process can not deny itself at will, because you do not know when, you are suddenly taken care of by the historical process.
Starting with threading, although threading has become an important concept in the programming world, developers have come to realize its pain point over the years of use:
It is difficult for threads (asynchronous code) to interact with each other, and they often have to use callback. A large number of callback will make the code difficult to read and understand, and eventually make the project difficult to maintain.
To put it simply, it is more convenient for threads to interact with each other on the developer side.
And what can Xiecheng do here?
Maybe I'll restate the sore point of threads: how threads can collaborate more easily on the developer side.
In retrospect, how did we introduce Xiecheng? Collaborative multitasking, right? remember the collaboration between the turntable and the machine hand in the picture above? We said at the time that the two tasks were more like the collaboration of two functions, but what if the turntable and the machine hand were treated as two threads? With the help of the compiler, the thread is encapsulated into functions that can be paused and resumed, can the thread cooperate as designed by the co-program?
Let's take a look at how collaborative programs are used today at the code level. Design a simple requirement: when users in the community post, they need to verify the posting permissions from the background and request two interfaces, then we may need to try to open two threads to complete it.
Normal callback code:
Fun tryPost () {/ / first verify permissions through the API (actually start a thread, and then wait for callback) findUserPermission (user,callback ()) {public void onSuccess (UserPermission response) {/ / callback if successful, check whether you have permission if (response.hasPermission) {/ / if you have permission Then access the posting interface (also open the thread Waiting for callback) postContent (content Callback () {public void onSuccess (Result response) {/ / handle successful response} public void onFail () {} else {/ / if you don't have permission Then. }} public void onFail () {}
This is a relatively common practice, we need to access the interface twice, and the interaction can only be carried out in callback, but in fact, the code is already very ugly, if there is any other logic, the code will only be more jumbled and difficult to maintain.
So how does Xiecheng solve this pain point? Let's take a look at how the code of the (kotlin and python) collaboration program implements this requirement:
The co-program code of kotlin
/ / the function is identified by the suspend keyword and can be called by the cooperative program. It has the ability to suspend and resume. In fact, the io thread is still used to complete the interface request suspend fun tryfindUserPermission (): PermissionResponse {return withContext (Dispatchers.IO) {findUserPermission (user)}} / / the function is identified by the suspend keyword. Can be called by the suspend fun post (): Result {return withContext (Dispatchers.IO) {postContent (content)} fun tryPost () {/ / start a launch {/ / code to be executed on this line, give up the cpu, enter the paused state, and wait for the request to succeed. Will resume execution) var response = tryfindUserPermission () / / access user rights to the backend if (response.hasPermission) {/ / start posting if you have permission (open thread, give up cpu, suspend execution, wait for resumption) var response = post () / / handle response if need}
As you can see, in kotlin, the co-program encapsulates the code in the thread into a function that can pause / resume, making the interaction between multiple threads as simple as a normal function without the need for callback.
The co-program code of python
The keyword import asyncio / / async indicates that this function can be called by the async def findUserPermission (): / / handle http request. Return response async def postContent (): / / handle http request. Return response async def main (): / / an attempt to obtain permission information will also give up cpu, enter a paused state, and wait for reponse = await findUserPermission () / / to determine that permission is available. If response.hasPermission: res = await postContent () / / handle response if need asyncio.run (main ())
Python deals with this problem through a collaborative process, which is essentially the same as kotlin.
I believe you can see that the expression of Xiecheng is different in different languages.
Through the above pseudo-code, we can see clearly that the cooperative program can significantly simplify the complexity of cooperation between threads, so that we can write asynchronous code by writing synchronous code, greatly simplifying your logic and making your code easy to maintain.
So how does Xiecheng do it?
Although the cooperation programs are different in different languages, the principles are all the same. The compilers of programming languages modify the function by some keywords (async in suspend,python in kotlin) and generate some thread-related code during compilation to achieve the function of pausing and resuming the function, thus leaving thread-related code to be generated during compilation. At the development level, it can provide a way of collaboration like ordinary functions.
Because of solving this pain point, collaborative process began to become more and more popular with developers. The coprogram saves the thread-related code during compilation with the help of the compiler, and the developer can use the thread by operating the coprogram, so it is now considered to be a lightweight thread.
For multi-threaded collaboration, or cooperation between asynchronous code is not the only solution, in JS, there are promise,Java, RxJava and so on, they are committed to solving the problems related to asynchronous programming, hoping to write synchronous code to write asynchronous code, so far, they are doing very well.
Thank you for your reading, the above is the content of "how to understand Kotlin Program". After the study of this article, I believe you have a deeper understanding of how to understand Kotlin Program, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.