Package sync
type 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 (*WaitGroup) Add
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.
func (*WaitGroup) Done
func (wg *WaitGroup) Done()
Done decrements the WaitGroup counter.
func (*WaitGroup) Wait
func (wg *WaitGroup) Wait()
Wait blocks until the WaitGroup counter is zero.
大体意思是:通过使用,可以阻塞主线程,直到相应数量的子线程结束。package main
import "fmt"
func Add(x, y int) {
("%d + %d = %d\n", x, y, x+y)
}
func main() {
for i := 1; i <= 10; i++ {
go Add(i, i)
}
}
运行程序:
C:/go/bin/ run [E:/project/go/lx/src]
成功: 进程退出代码 0.
上面的例子,之所以没有看到任何的输出,是因为子线程还没有来得及运行,主线程已经结束了,导致了程序的直接退出。
. 正确的例子如下(使用WaitGroup)
package mainimport "fmt"import "sync"func Add(x, y int, wg *) {("%d + %d = %d\n", x, y, x+y)()
}func main() {const MAX_GOROUTINES = 10var wgfor i := 1; i <= MAX_GOROUTINES; i++ {(1)}
for i := 1; i <= MAX_GOROUTINES; i++ {go Add(i, i, &wg)}
()
}运行程序:
C:/go/bin/ run [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
成功: 进程退出代码 0.
package main
import "fmt"
func Add(x, y int, ch chan int) {
("%d + %d = %d\n", x, y, 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, i, chs[i])
}
for i := 0; i < len(chs); i++ {
<-chs[i]
}
}运行程序:
C:/go/bin/ run [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
成功: 进程退出代码 0.