go-concurrency-patterns icon indicating copy to clipboard operation
go-concurrency-patterns copied to clipboard

What happens to the anonymous goroutine running in the background?

Open BSardorbek opened this issue 2 years ago • 1 comments

https://github.com/kevchn/go-concurrency-patterns/blob/9493f7e9f5db056eae29c2faa231ea54c5514545/1-8-timeout-select.go#L29


func generator(msg string) <-chan string { // returns receive-only channel
	ch := make(chan string)
	go func() { // anonymous goroutine
		for i := 0; ; i++ {
			ch <- fmt.Sprintf("%s %d", msg, i)
			time.Sleep(time.Second)
		}
	}()
	return ch
}

BSardorbek avatar May 13 '23 11:05 BSardorbek

The goroutine, still running in the background, continues its infinite loop. However, since the main code is no longer receiving from the channel, the goroutine's actions are effectively ignored. The Go runtime will eventually clean up the goroutine when the program exits.

younesious avatar Apr 10 '24 22:04 younesious