Learning-Go-zh-cn icon indicating copy to clipboard operation
Learning-Go-zh-cn copied to clipboard

请问并发章节的 Q26 (1) channel 第二题的答案是否有问题?

Open bwangelme opened this issue 6 years ago • 0 comments

这一题的答案在这里:

https://github.com/mikespook/Learning-Go-zh-cn/blob/master/ex-channels/src/for-quit-chan.go

它的代码是这样的:

func main() {
	ch := make(chan int)
	quit := make(chan bool)
	go shower(ch, quit)
	for i := 0; i < 10; i++ {
		ch <- i
	}
	quit <- false	// 或者是 true,这没啥关系
}

func shower(c chan int, quit chan bool) {
	for {
		select {
		case j := <-c:
			fmt.Printf("%d\n", j)
		case <-quit:
			break
		}
	}
}

main 程序在将false写入quitchannel后就退出了,此时是不是仍然有可能shower Goroutine 没有从quit中接收到值,整个程序已经结束了。

我感觉这个逻辑应该是show Goroutine 写入值到quitchannel中,然后main再等待结束吧。

package main

import "fmt"

func show(ch chan int, quit chan bool) {
	for {
		val, ok := <-ch
		if !ok {
			break
		}
		fmt.Println("Get the", val)
	}

	quit <- true
}

func main() {
	ch := make(chan int)
	quit := make(chan bool)

	go show(ch, quit)
	for i := 0; i < 10; i++ {
		ch <- i
	}
	close(ch)

	<-quit
}

bwangelme avatar Jul 20 '18 00:07 bwangelme