GOLANG sync.WaitGroup讲解

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.

大体意思是:通过使用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, 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

成功: 进程退出代码 0.

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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值