使用channel同步
package main
import (
"fmt"
)
func printNumber(num int, c chan struct{}) {
fmt.Println(num)
c <- struct{}{}
}
func main() {
sign := make(chan struct{}, 10)
for i:=0;i<10;i++ {
go printNumber(i, sign)
}
for i:=0;i<10;i++{
<-sign
}
fmt.Println("Done.")
}
使用sync.WaitGroup
package main
import (
"fmt"
"sync"
)
func printNumber(num int, callback func()) {
fmt.Println(num)
callback()
}
func main() {
var wg sync.WaitGroup
wg.Add(10)
for i:=0;i<10;i++ {
go printNumber(i, wg.Done)
}
wg.Wait()
fmt.Println("Done.")
}
原文地址:https://www.cnblogs.com/linyihai/p/10465950.html
时间: 2024-10-19 09:23:27