使用同步锁同步:
package main
import "fmt"
import "time"
import "sync"
func main() {
var wg sync.WaitGroup
//生成带缓存的chan
var limit = make(chan struct{}, 10)
for i := 0; i < 100; i++ {
//写入chan,直到缓存写满阻塞,即限制协程数
limit <- struct{}{}
//同步计数加1
wg.Add(1)
go func(i int) {
time.Sleep(1000 * time.Millisecond)
fmt.Println(i)
//协程内任务完成读取chan,主协程可继续写入chan
<-limit
//同步计数减1
defer wg.Done()
}(i)
}
//同步阻塞直到计数为0,即所有协程完成
wg.Wait()
}
使用channel同步:
package main
import "fmt"
import "time"
var sync chan int;
func foo(i int) {
fmt.Println(i)
time.Sleep(time.Second)
sync <- 0
}
func main() {
count := 100
sync = make(chan int, count)
for i := 0; i < count; i++ {
go foo(i)
}
//等待所有协程完成
for i := 0; i < count; i++ {
<-sync
}
}
标签:none