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

边栏推荐
- 思迈特软件Smartbi完成C轮融资,推动国产BI加速进入智能化时代
- Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice
- Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
- JS inheritance method
- 1w5 words to introduce those technical solutions of distributed system in detail
- 1w5字详细介绍分布式系统的那些技术方案
- How does QT delete all controls in a layout?
- PHP基础知识 - PHP 使用 MySQLI
- Network interface network crystal head RJ45, Poe interface definition line sequence
- Warehouse of multiple backbone versions of yolov5
猜你喜欢

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

Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice

Argocd Web UI loading is slow? A trick to teach you to solve

我来教你如何组装一个注册中心?

Huid learning 7: Hudi and Flink integration

ciou损失

CAT1 4g+ Ethernet development board 232 data is sent to the server through 4G module TCP

C轮融资已完成!思迈特软件领跑国内BI生态赋能,产品、服务竿头一步

bash-shell 免交互
![[opencv] generate transparent PNG image](/img/0a/4afc9bda411634562f4b0f3915a7ba.png)
[opencv] generate transparent PNG image
随机推荐
Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
SQL server time field sorting
oracle sql 问题
Blog Building 9: add search function to Hugo
Shell programming specifications and variables
创建线程的3种方式
Introduction to self drive tour of snow mountains in the West in January 2018
解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
图片批处理|必备小技能
This flick SQL timestamp_ Can ltz be used in create DDL
GBase 8a MPP与银河麒麟(x86版)完成深度适配
招贤纳士,GBASE高端人才招募进行中
[opencv] generate transparent PNG image
Warehouse of multiple backbone versions of yolov5
Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
Eight ways to solve EMC and EMI conducted interference
bash-shell 免交互
Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
[soft test software evaluator] 2013 comprehensive knowledge over the years
C轮融资已完成!思迈特软件领跑国内BI生态赋能,产品、服务竿头一步