1. 用Mutex实现
package main
import (
"fmt"
"sync"
)
var num int
var mtx sync.Mutex
var wg sync.WaitGroup
func add() {
mtx.Lock()
defer mtx.Unlock()
defer wg.Done()
num += 1
}
func main() {
for i := 0; i < 100; i++ {
wg.Add(1)
go add()
}
wg.Wait()
fmt.Println("num:", num)
}
2. 使用chan实现
package main
import (
"fmt"
"sync"
)
var num int
func add(h chan int, wg *sync.WaitGroup) {
defer wg.Done()
h <- 1
num += 1
<-h
}
func main() {
ch := make(chan int, 1)
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go add(ch, wg)
}
wg.Wait()
fmt.Println("num:", num)
}
有疑问加站长微信联系(非本文作者)