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

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

Open
MiddleTier98 opened this issue Apr 11, 2023 · 0 comments
Open

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

MiddleTier98 opened this issue Apr 11, 2023 · 0 comments

Comments

@MiddleTier98
Copy link

原题: 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)
}
@MiddleTier98 MiddleTier98 changed the title 『goroutine和channel使用一』 答案有隐含的漏洞 『goroutine和channel使用一』 答案协程泄露 Apr 11, 2023
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