读取空的channel会根据channel类型返回空的数据,所以需要判断channel读取是否成功,i,
ok <- c,判断ok的值
我的解答
解析题目,10个goroutine,但是需要依次打印1-10000,
import ( "fmt" "time" )
var IsRunning = true
funcprint(gid int, m map[int]chanint) { curChan := m[gid] nextChan := m[(gid+1)%10] for IsRunning { select { case i, ok := <-curChan: if ok { fmt.Println(fmt.Sprintf("%d goroutine id=%d", i, gid)) i++ if i > 10000 { IsRunning = false } else { nextChan <- i } } } }
}
funcprintInOrder() {
memo := map[int]chanint{} for i := 0; i < 10; i++ { c := make(chanint, 1) memo[i] = c } fmt.Printf("%#+v\n", memo)
for i := 0; i < 10; i++ { goprint(i, memo) } firstChan := memo[0] firstChan <- 0 for IsRunning { // time.Sleep(time.Millisecond) } deferfunc() { for k, c := range memo { fmt.Printf("关闭: %d\n", k) close(c) } }() }