加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

GOLANG sync.WaitGroup讲解

发布时间:2020-12-16 18:13:40 所属栏目:大数据 来源:网络整理
导读: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 tim

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 = %dn", 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 = %dn", 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. 正确的例子如下(使用channel)
package main
 
 
import "fmt"
 
 
func Add(x, ch chan int) {
fmt.Printf("%d + %d = %dn", 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读