当前位置:网站首页>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 .

边栏推荐
- PHP Basics - PHP uses mysqli
- Sliding screen switching on uniapp supports video and image rotation, similar to Tiktok effect
- [soft test software evaluator] 2013 comprehensive knowledge over the years
- Blog Building 9: add search function to Hugo
- [mindspire YiDianTong robot-01] you may have seen many Knowledge Q & A robots, but this is a little different
- Pyspark writes data to iceberg
- [opencv] generate transparent PNG image
- JS inheritance method
- Argocd Web UI loading is slow? A trick to teach you to solve
- Bash shell interaction free
猜你喜欢

The current value of uniapp's swiper dynamic setting does not take effect solution

思迈特软件Smartbi完成C轮融资,推动国产BI加速进入智能化时代

GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览

Hcip --- LDP and MPLS Technology (detailed explanation)

客户至上 | 国产BI领跑者,思迈特软件完成C轮融资

置顶各大平台,22版面试核心知识解析笔记,强势上榜

Blog Building 9: add search function to Hugo
![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]

Shell编程规范与变量

Use of tkmapper - super detailed
随机推荐
Blog building 7: Hugo
PHP Basics - PHP uses mysqli
MySQL how to add users and set permissions?
A new method of exposing services in kubernetes clusters
Day112. Shangyitong: Mobile verification code login function
Slice function of JS handwriting function (thoroughly understand the header but not the footer)
PHP基础知识 - PHP 使用 MySQLI
Quickly build a gateway service, dynamic routing and authentication process, and watch the second meeting (including the flow chart)
Basic syntax of jquey
Oracle SQL problems
Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation
Div tags and span Tags
Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
Why can ThreadLocal achieve thread isolation?
Service current limiting and fusing of micro service architecture Sentinel
Three ways to create threads
Smart software completed round C financing, making Bi truly "inclusive"
Hcip day 8
Introduction to self drive tour of snow mountains in the West in January 2018
Hyperlink label