We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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可以正常退出,但是负责打印数字的goroutine是一个死循环,因此示例代码存在泄露goroutine的风险
go func() { i := 1 for { select { case <-number: fmt.Print(i) i++ fmt.Print(i) i++ letter <- true } } }()
负责打印字母的goroutine在退出时可以执行close(number)告知打印数字的goroutine退出
close(number)
package main import ( "fmt" "sync" ) func main() { letter, number := make(chan bool), make(chan bool) wg := sync.WaitGroup{} wg.Add(1) go func() { defer func() { fmt.Println("\nNumber goroutine exit.") wg.Done() }() i := 1 for range number { fmt.Print(i) i++ fmt.Print(i) letter <- true } }() wg.Add(1) go func(wg *sync.WaitGroup) { defer func() { close(number) fmt.Println("\nLetter goroutine exit.") wg.Done() }() i := 'A' for range letter { if i >= 'Z' { return } fmt.Print(string(i)) i++ fmt.Print(string(i)) i++ number <- true } }(&wg) number <- true wg.Wait() }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Goroutine是如何泄露的
在交替打印数字和字母的解法里面,负责打印字母的goroutine可以正常退出,但是负责打印数字的goroutine是一个死循环,因此示例代码存在泄露goroutine的风险
解决办法
负责打印字母的goroutine在退出时可以执行
close(number)
告知打印数字的goroutine退出The text was updated successfully, but these errors were encountered: