这个题目要求有10个协程,每个协程打印0-9作为后缀的数字,总共打印100个
package main
import (
"context"
"time"
)
// 每个线程只输出后缀是0-9的数字
func getPrintSuffixNumberFn(key int, finishNum int, allDone chan bool) func(ctx context.Context, cs [10]chan int) {
return func(ctx context.Context, cs [maxSuffix]chan int) {
nextKey := (key + 1) % 10
for ; ; {
select {
case v := <-cs[key]:
println(v)
time.Sleep(time.Nanosecond * 1)
if v == finishNum {
allDone <- true
break
}
cs[nextKey] <- v + 1
case <-ctx.Done():
break
}
}
}
}
// 定义后缀的数量,也可以改成100,每个协程打印后缀为0-99的数字
const maxSuffix = 10
func main() {
// allDone waits for all goroutines finished theirs jobs.
var allDone = make(chan bool)
var cs [maxSuffix]chan int
var finishNum = 100
// init channel
for i := 0; i < maxSuffix; i++ {
cs[i] = make(chan int)
}
// generate all keys
ctx, cancel := context.WithCancel(context.TODO())
for i := 0; i < maxSuffix; i++ {
fn := getPrintSuffixNumberFn(i, finishNum, allDone)
go fn(ctx, cs)
}
cs[1] <- 1
<-allDone
// 主动退出协程
cancel()
}
网友评论