lifei6671 / interview-go

golang面试题集合

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

『goroutine和channel使用一』 答案协程泄露

codeman98 opened this issue · comments

原题: https://github.com/lifei6671/interview-go/blob/master/question/q009.md
答案中done <- true 后面应该加上 return,否则子协程不会立刻退出, 往已经关闭的 done 写数据
如果此后做一些处理的话就会触发 panic

当函数被循环调用时, 必现 panic: send on closed channel

func main() {
	random := make(chan int)
	done := make(chan bool)

	go func() {
		for {
			num, ok := <-random
			if ok {
				fmt.Println(num)
			} else {
				done <- true
			}
		}
	}()

	go func() {
		defer close(random)

		for i := 0; i < 5; i++ {
			random <- rand.Intn(5)
		}
	}()

	<-done
	close(done)
        // 触发 panic
        time.Sleep(1 * time.Second)
}