当前位置:网站首页>Go waitgroup and defer
Go waitgroup and defer
2022-07-28 08:54:00 【go|Python】
List of articles
WaitGroup And defer
WaitGroup
WaitGroup It's a structural type , Used to wait for a batch of Go The implementation of the cooperative program is over . The program will block all the time , Until all these processes are completed . The main thread (goroutine) Will execute
WaitGroup Use
Through the previous channel , We can use channel to realize and waitgroup Same effect . The code is as follows :
func main() {
fmt.Println(" Program starts ")
c := make(chan int, 5)
for i := 0; i < 5; i++ {
go Test(i, c)
}
for i:=0; i<cap(c);i++{
// It can't be used here len, The reason lies in , Lord goroutine At this point , Other goroutine It may not be finished , therefore channel c The length in is not equal to 5. Will be submitted to the deadlock error
<- c
}
fmt.Println(" Program end ")
}
func Test(s int, c chan int) {
fmt.Println(s)
c <- s
}
` Program starts 4 0 1 2 3 Program end `
It can be seen that , wait for 5 Height goroutine perform , The code is a bit complicated , If you have to wait more , Although the amount of code will not increase , however The capacity of the channel really needs change . Next, let's look at using waitgroup Implemented code .
func main() {
fmt.Println(" Program starts ")
// WaitGroup yes Structure , Value type , There is a default zero value without initialization ; When parameters are passed , If you change the original , Need to get the address
var wg = sync.WaitGroup{
}
for i := 0; i < 5; i++ {
go Test2(i, &wg)
wg.Add(1) // Start a task every cycle
}
//wg.Add(5) // It can also be started at one time 5 individual
wg.Wait() // Wait for all tasks to complete
fmt.Println(" Program end ")
}
func Test2(s int, wg *sync.WaitGroup) {
fmt.Println(s)
wg.Done() // End a task
}
It can be seen that , Use waitgroup, The code is much simpler , One more penny goroutine, Just start one more task .
defer
defer The purpose of the statement is : contain defer Function of statement , Before the function will return , Call another function . This definition may seem complicated , We can easily understand it through an example .
func main() {
Test3()
}
func Test3() {
defer finally() // To register first , After execution
// finally()
fmt.Println("Test3: I started to execute ")
fmt.Println("Test3: My execution is over ")
}
func finally() {
fmt.Println(" It's time for me to execute ")
}
` Use defer Print the results : Test3: I started to execute Test3: My execution is over It's time for me to execute `
` Don't use defer Print the results : It's time for me to execute Test3: I started to execute Test3: My execution is over `
In short, it's : Registration code , Delay call , After the function is executed , Execute in reverse order of registration defer, Registered first , Finally, execute .
also defer, It can not only be used in functions , It can also be used for method calls . If you are interested, you can try it yourself .
Parameter value
stay Go In language , The arguments are not determined when the deferred function is called , But when executing defer At the time of statement , The arguments of the delay function are evaluated .
Through an example , It can be well understood
func main() {
i := 4
defer finally(i) // Parameters have been passed in when defining , It's just not implemented yet
defer finally(&i)
i++
}
func finally(i int) {
fmt.Println(i) // 4
}
func finally2(i *int) {
fmt.Println(*i) // 5
}
` 5 4 `
therefore , Value type data use defer After a function parameter is passed , A change in value does not affect defer Parameters of the post function . But the reference type will affect .
defer Stack
When a function is called more than once defer when ,Go Will be able to defer Call into a stack , Then follow the last in, first out (Last In First Out, LIFO) Sequential execution . The code example can be seen above .

边栏推荐
- Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice
- Day112. Shangyitong: Mobile verification code login function
- Analysis and recurrence of network security vulnerabilities
- PHP基础知识 - PHP 使用 MySQLI
- Kubernetes technology and Architecture (VII)
- 模型预测控制(MPC)解析(九):二次规划的数值解(下)
- PostgreSQL:无法更改视图或规则使用的列的类型
- 创建线程的3种方式
- A new method of exposing services in kubernetes clusters
- How to execute the SQL assembled in ODPs SQL function and get the return value?
猜你喜欢

Ciou loss

快速搭建一个网关服务,动态路由、鉴权的流程,看完秒会(含流程图)

49 opencv deep analysis profile

Competition: diabetes genetic risk detection challenge (iFLYTEK)

HCIP---LDP和MPLS技术(详解)

Recruiting talents, gbase high-end talent recruitment in progress

Hcip day 8
![Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]](/img/9c/b4ebe608cf639b8348adc1f1cc71c8.png)
Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]

Let me teach you how to assemble a registration center?

Why setting application.targetframerate doesn't work
随机推荐
博客搭建七:hugo
NDK series (6): let's talk about the way and time to register JNI functions
How to execute the SQL assembled in ODPs SQL function and get the return value?
Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
A new method of exposing services in kubernetes clusters
HCIP---LDP和MPLS技术(详解)
Eight ways to solve EMC and EMI conducted interference
Introduction of functions in C language (blood Book 20000 words!!!)
View the dimensions of the list
Distributed system architecture theory and components
What content does the new version of network security level protection evaluation report template contain? Where can I find it?
PostgreSQL:无法更改视图或规则使用的列的类型
Let me teach you how to assemble a registration center?
Digital signatures and Ca certificates
How CI framework integrates Smarty templates
Pyspark changes the column order and saves it into iceberg database
49 opencv deep analysis profile
Chapter 2-14 sum integer segments
Two dimensional array and operation
Data fabric, next air outlet?