Saki's 研究记录

Go 使用协程编写程序,按顺序打印 cat、dog、fish依次打印十次

字数统计: 174阅读时长: 1 min
2023/12/17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import (
"fmt"
"sync"
)

func main() {
var wg sync.WaitGroup

chCatOk := make(chan struct{})
defer close(chCatOk)
chDogOk := make(chan struct{})
defer close(chDogOk)
chFishOk := make(chan struct{})
defer close(chFishOk)
stopCh := make(chan struct{})

wg.Add(3)
go PrintAnimal(&wg, "cat", &chCatOk, &chDogOk, &stopCh)
go PrintAnimal(&wg, "dog", &chDogOk, &chFishOk, &stopCh)
go PrintAnimal(&wg, "fish", &chFishOk, &chCatOk, &stopCh)

chCatOk <- struct{}{}
wg.Wait()

fmt.Println("done")
}

func PrintAnimal(wg *sync.WaitGroup, name string, ch1, ch2, stop *chan struct{}) {
defer wg.Done()
count := 0

for {
select {
case <-*ch1:
fmt.Println(name, count)
count++
if count >= 100 {
fmt.Println(name, "over")
close(*stop)
return
}
*ch2 <- struct{}{}
case <-*stop:
fmt.Println(name, "stop")
return
}
}
}

以上。

CATALOG