有个缺点: 控制n个goroutine就需要创建n个chan
package controllgoroutine
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func ControlGoroutineExeSequence() {
ch1 := make(chan struct{}, 1)
ch2 := make(chan struct{}, 1)
ch3 := make(chan struct{}, 1)
ch1 <- struct{}{} // 必须要有容量为1的buf,否则这里就会阻塞
wg.Add(3)
go func(gid int, in, out chan struct{}) {
select {
case <-in:
fmt.Printf("goroutune: %v\n", gid)
out <- struct{}{} // 打印完就传信号给另一个chan执行!
}
wg.Done()
}(1, ch1, ch2)
go func(gid int, in, out chan struct{}) {
select {
case <-in:
fmt.Printf("goroutune: %v\n", gid)
out <- struct{}{}
}
wg.Done()
}(2, ch2, ch3)
go func(gid int, in, out chan struct{}) {
select {
case <-in:
fmt.Printf("goroutune: %v\n", gid)
out <- struct{}{}
}
wg.Done()
}(3, ch3, ch1)
wg.Wait()
}