Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle and usage analysis of Go protocol implementation?

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about the implementation principle and use analysis of Go. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

The principle of Go concurrent programming

The implementation of the Go language is called goroutine and is managed by the Go runtime. Concurrent programming through the Go language is very simple: we can enable multiple programs through the keyword go in a processing process, and then complete different subtasks in different programs. The programs that these users create and maintain in the code are essentially user-level threads. At the bottom of the Go language runtime, the user-level thread is handed over to the system-level thread of the operating system through the scheduler. If the user-level thread is suspended due to an IO operation, the scheduler will separate the user-level thread from the system-level thread so that the system-level thread can handle other user-level threads. When the IO operation is completed, it needs to resume running. The scheduler will schedule idle system-level threads to process this user-level thread, so as to achieve the purpose of concurrent processing of multiple co-programs. In addition, the scheduler will also apply to the operating system to create new system-level threads when there are not enough system-level threads, and destroy some idle threads in the case of too many system-level threads, this process is somewhat similar to the working mechanism of PHP-FPM, in fact, this is also the working mechanism of many process / thread pool managers, which can ensure the efficient use of system resources and avoid the waste of system resources.

The above is the unique implementation model of concurrent programming in Go language.

Simple example of cooperative program

The following is a simple example to demonstrate how to do concurrent programming through a co-program in the Go language. We write an addition function add in add.go and call it through a co-program:

Package main

Import "fmt"

Func add (a, b int) {var c = a + b; fmt.Printf ("% d +% d =% d", a, b, c)}

Func main () {go add (1,2)}

Well, it's that simple. There are two coprograms in this code, one is explicit, and the statement declared by the go keyword means that a new coprogram is enabled to handle addition operations, and the other is implicit, that is, the main function itself runs in a main coprogram. The co-program and the subroutine that calls the add function are two co-programs that run concurrently, just like starting with the go keyword. Fork a new road from the main cooperation. Compared with the previous way of not using the co-program, this also introduces uncertainty: we do not know when the sub-co-program is completed and what state it is running to. After the promoter in the main co-program, the program exits, which means that the processing process containing these two co-routines exits, so when we run this code, we will not see the printed results running in the sub-co-routine. because the process exited before it could execute them. In addition, we should not try to return the processing result from the add function, because the return value of the subroutine cannot be obtained at all in the master program, and it has nothing to do with the master routine since it was executed, and the return value will be discarded.

If you want to display the printed results of the subroutine, one way is to wait long enough in the main program before exiting to ensure that all the code in the subroutine is finished:

Package main

Import ("fmt"time")

Func add (a, b int) {var c = a + b; fmt.Printf ("% d +% d =% d\ n", a, b, c)}

Func main () {go add (1,2) time.Sleep (1e9)}

Here, we use time.Sleep (1e9) to tell the master to wait for 1 second before exiting, so that we can run go run add.go to see the printed result:

However, this approach is too simple and crude, and 1 second is certainly enough for addition operations (and it doesn't take that long at all), but what about hard-to-predict operations such as database connections and sending e-mails? This approach is not appropriate, we need a more precise way to exit the main program immediately after the execution of the subprogram, which involves communication between the programs, which we will focus on in the next tutorial and rewrite this code through inter-program communication.

Concurrent execution example

So far, we have only demonstrated the startup and simple use of the Go language protocol, but the above code is not enough to verify that the program is executed concurrently. Next, we verify the concurrent execution of the program through the following code:

Package main

Import ("fmt"time")

Func add (a, b int) {var c = a + b; fmt.Printf ("% d +% d =% d\ n", a, b, c)}

Func main () {for I: = 0; I < 10; iTunes + {go add (1, I)} time.Sleep (1e9)}

Very simply, we can put a loop on the outer layer of the co-program code, so that 10 subprograms are started at the same time. Because they are executed concurrently, the order of execution cannot be guaranteed. So we see the print result like this:

If you are still worried, you can add the following code at the end of the add function:

Time.Sleep (3e9)

It means that each sub-program sleeps for 3 seconds before exiting after executing the print statement. If it is not executed concurrently, then at most one result can be printed, but the reality is that 10 results are still printed without any delay. It is proved that these addition operations are executed concurrently.

The above is the principle and usage analysis of Go protocol shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report