This is a creation in Article, where the information may have evolved or changed.
1.defer Panic Recover
defer : Golang's defer elegant and concise, is one of the highlights of Golang. Defer does not execute immediately at the time of Declaration, but after the function return, executes each defer in turn, in order to release resources, clean up data, log logs, exception handling, and so on.
The contents of the defer definition must be written between return, otherwise it will not defer.
f, err := os.Open("file")
defer f.Close()
if err != nil { //判断是否出错用 err != nil 来判断
return
}
println(string(b))
defer的智行顺序:结果是one,two,three从下向上一次执行
Func defertest (number int) int {
Defer func () {number++fmt. Println ("Three:", Number)} () defer func () {number++fmt. Println ("Both:", Number)} () defer func () {number++fmt. Println ("One:", Number)} () return number}
2.go async.WaitGroup,它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成。
WaitGroup总共有三个方法:Add(delta int),Done(),Wait()。
Add:添加或者减少等待goroutine的数量
Done:相当于Add(-1)
Wait:执行阻塞,直到所有的WaitGroup数量变成0
var waitGroup sync.WaitGroup //定义一个同步等待的组
也可以这样生成:
waitGroup
:= &sync.WaitGroup{}
waitGroup.Add(1) //添加一个计数
go function() {} //执行任务
waitGroup.Wait() //阻塞直到所有任务完成
Package Mainimport ("FMT" "Sync" "Time") Func main () {var wg sync. Waitgroupfor I: = 0; I < 5; i = i + 1 {WG. ADD (1) go func (n int) {//Defer WG. Done () defer WG. ADD ( -1) echonumber (n)} (i)}WG. Wait ()}func echonumber (i int) {time. Sleep (3e9) fmt. Println (i)}
The program is simple, just output the number of each loop over 3 seconds. Then, if the program does not waitgroup, then the output will not be visible. Because the Goroutine has not finished, the main thread has been executed. Note the defer WG. Done () and defer WG. ADD (-1) acts the same. This is good, the original execution script, all use time. Sleep, with an estimated time until the child thread finishes executing. Waitgroup is very good. Although Chanel can be implemented, it feels good if it involves not having a child thread synchronizing with the main thread data.
Remark: https://studygolang.com/articles/319