GOLANG sync.WaitGroup讲解

前端之家收集整理的这篇文章主要介绍了GOLANG sync.WaitGroup讲解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Package sync

typeWaitGroup

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

WaitGroup) Done()

Done decrements the WaitGroup counter.

func (*WaitGroup)Wait

WaitGroup) Wait()

Wait blocks until the WaitGroup counter is zero.

大体意思是:通过使用sync.WaitGroup,可以阻塞主线程,直到相应数量的子线程结束。
e.g. 该例子没有使用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]

成功: 进程退出代码 0.

 
 
上面的例子,之所以没有看到任何的输出,是因为子线程还没有来得及运行,主线程已经结束了,导致了程序的直接退出
e.g. 正确的例子如下(使用WaitGroup)
package main
import "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 = 10
var wg sync.WaitGroup
for 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

e.g. @H_854_403@正确的例子如下(使用channel)
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

成功: 进程退出代码 0.

猜你在找的Go相关文章