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泄露问题——交替打印数字和字母 #69

Open
zhazhalaila opened this issue Feb 1, 2023 · 0 comments
Open

Goroutine泄露问题——交替打印数字和字母 #69

zhazhalaila opened this issue Feb 1, 2023 · 0 comments

Comments

@zhazhalaila
Copy link

zhazhalaila commented Feb 1, 2023

Goroutine是如何泄露的

在交替打印数字和字母的解法里面,负责打印字母的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退出

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()
}
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