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

边栏推荐
- Does gbase 8s support storing relational data and object-oriented data?
- Bash shell interaction free
- Argocd Web UI loading is slow? A trick to teach you to solve
- Do you know the five minute rule and the ten byte rule?
- Redis basic knowledge, let's review it
- Why setting application.targetframerate doesn't work
- 思迈特软件Smartbi完成C轮融资,推动国产BI加速进入智能化时代
- 阿里技术四面+交叉面+HR面,成功拿到offer,双非本科进不了大厂?
- 1w5字详细介绍分布式系统的那些技术方案
- 第2章-2 计算分段函数[1]
猜你喜欢

说透缓存一致性与内存屏障

Uniapp ---- detailed steps to obtain the longitude and latitude of the current position and other information (including applet)

JS inheritance method

Basic syntax of jquey

阿里技术四面+交叉面+HR面,成功拿到offer,双非本科进不了大厂?

SQL Server查询结果导出到EXCEL表格

49 opencv deep analysis profile

You're not still using xshell, are you? This open source terminal tool is yyds!

A new method of exposing services in kubernetes clusters

Solution: indexerror: index 13 is out of bounds for dimension 0 with size 13
随机推荐
Why can ThreadLocal achieve thread isolation?
Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice
SQL Server查询结果导出到EXCEL表格
Simple use of unity queue
Sliding screen switching on uniapp supports video and image rotation, similar to Tiktok effect
Hcip --- LDP and MPLS Technology (detailed explanation)
Service current limiting and fusing of micro service architecture Sentinel
Recycling of classes loaded by classloader
Analysis and recurrence of network security vulnerabilities
第2章-2 计算分段函数[1]
PostgreSQL:无法更改视图或规则使用的列的类型
Can‘t connect to server on ‘IP‘ (60)
Uniapp ---- detailed steps to obtain the longitude and latitude of the current position and other information (including applet)
Sparksql and flinksql create and link table records
Introduction of functions in C language (blood Book 20000 words!!!)
[soft test software evaluator] 2013 comprehensive knowledge over the years
View the dimensions of the list
(13) Simple temperature alarm device based on 51 single chip microcomputer
HCIP第八天
Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation