Skip to content

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

@MiddleTier98

Description

@MiddleTier98

原题: 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)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions