随笔记录,测试了一下经典的猫狗鱼Go协程并发经典实例,间隔一秒并发输出cat
dog fish 以及输出100次的代码,本实例考察,sync.WaitGroup的用法,以及协程按指定的顺序执行。
package main
func main(){
var wg sync.WaitGroup
catChan := make(chan struct{})
dogChan := make(chan struct{})
fishChan := make(chan struct{})
cat(&wg, catChan, fishChan)
dog(&wg, dogChan, catChan)
fish(&wg, fishChan, dogChan)
wg.Wait()
}
func cat(wg *sync.WaitGroup, catChan, fishChan chan struct{}) {
wg.Add(1)
go func() {
for {
fmt.Println("cat")
catChan <- struct{}{}
<-fishChan
}
wg.Done()
}()
}
func dog(wg *sync.WaitGroup, dogChan, catChan chan struct{}) {
wg.Add(1)
go func() {
for {
<-catChan
fmt.Println("dog")
dogChan <- struct{}{}
}
wg.Done()
}()
}
func fish(wg *sync.WaitGroup, fishChan, dogChan chan struct{}) {
wg.Add(1)
go func() {
for {
<-dogChan
fmt.Println("fish")
time.Sleep(1 * time.Second)
fishChan <- struct{}{}
}
wg.Done()
}()
}
// 打印100次
func cat(wg *sync.WaitGroup, catChan, fishChan chan struct{}) {
wg.Add(1)
go func() {
var counter int64
for counter <= 100 {
atomic.AddInt64(&counter, 1)
fmt.Println("cat")
catChan <- struct{}{}
<-fishChan
}
wg.Done()
}()
}
func dog(wg *sync.WaitGroup, dogChan, catChan chan struct{}) {
wg.Add(1)
go func() {
var counter int64
for counter <= 100 {
atomic.AddInt64(&counter, 1)
<-catChan
fmt.Println("dog")
dogChan <- struct{}{}
}
wg.Done()
}()
}
func fish(wg *sync.WaitGroup, fishChan, dogChan chan struct{}) {
wg.Add(1)
go func() {
var counter int64
for counter <= 100 {
atomic.AddInt64(&counter, 1)
<-dogChan
fmt.Println("fish")
fishChan <- struct{}{}
}
wg.Done()
}()
}