Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bwangelme opened this issue Jul 20, 2018 · 0 comments

Comments

@bwangelme
Copy link

这一题的答案在这里:

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant