大佬教程收集整理的这篇文章主要介绍了GOLANG sync.WaitGroup讲解,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time,Wait can be used to block until all goroutines have finished.
A WaitGroup must not be copied after first use.
type WaitGroup struct {
// contains filtered or unexported fields
}
func (wg *WaitGroup) Add(delta int)Add adds delta(增量),which may be negative,to the WaitGroup counter. If the counter becomes zero,all goroutines blocked on Wait are released. If the counter goes negative,Add panics.
WaitGroup) Done()
Done decrements the WaitGroup counter.
WaitGroup) Wait()
Wait blocks until the WaitGroup counter is zero.
大体意思是:通过使用sync.WaitGroup,可以阻塞主线程,直到相应数量的子线程结束。package main
import "fmt"
func Add(x, y int) {
fmt.Printf("%d + %d = %d\n", x, y, x+y)
}
func main() {
for i := 1; i <= 10; i++ {
go Add(i, i)
}
运行程序:
C:/go/bin/go.exe run test2.go [E:/project/go/lx/src]
上面的例子,之所以没有看到任何的输出,是因为子线程还没有来得及运行,主线程已经结束了,导致了程序的直接退出。
e.g. 正确的例子如下(使用WaitGroup)
package mainimport "fmt"import "sync"func Add(x, y int, wg *sync.WaitGroup) {fmt.Printf("%d + %d = %d\n", x+y)wg.Done()}func main() {const MAX_GOROUTINES = 10var wg sync.WaitGroupfor i := 1; i <= MAX_GOROUTINES; i++ {wg.Add(1)
}for i := 1; i <= MAX_GOROUTINES; i++ {go Add(i, i, &wg)}wg.Wait()}运行程序:
C:/go/bin/go.exe run test.go [E:/project/go/lx/src]10 + 10 = 20
1 + 1 = 2
6 + 6 = 12
7 + 7 = 14
8 + 8 = 16
9 + 9 = 18
3 + 3 = 6
5 + 5 = 10
2 + 2 = 4
4 + 4 = 8
package main
import "fmt"
func Add(x, ch chan int) {
fmt.Printf("%d + %d = %d\n", x+y)
ch <- 1
}
func main() {
chs := make([]chan int, 10)
for i := 0; i < len(chs); i++ {
chs[i] = make(chan int, 1)
go Add(i, chs[i])
}
for i := 0; i < len(chs); i++ {
<-chs[i]
}
}运行程序:
C:/go/bin/go.exe run test2.go [E:/project/go/lx/src]
2 + 2 = 4
0 + 0 = 0
5 + 5 = 10
3 + 3 = 6
1 + 1 = 2
9 + 9 = 18
4 + 4 = 8
8 + 8 = 16
6 + 6 = 12
7 + 7 = 14
以上是大佬教程为你收集整理的GOLANG sync.WaitGroup讲解全部内容,希望文章能够帮你解决GOLANG sync.WaitGroup讲解所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。