merfrei
(Emiliano Rudenick)
January 21, 2020, 11:41pm
1
Hello everyone
I have this code as example. Something similar happens to me in a bigger project I am working on.
https://play.golang.org/p/eiFA6yuvpOa
Can anyone explain to me why the last number is lost? When I execute the code 9 is missing. I do not understand why it happens.
Thanks
merfrei
(Emiliano Rudenick)
January 22, 2020, 1:31am
2
Looks like I was doing all wrong
I noticed my error, here the solution:
https://play.golang.org/p/4gDVCC3uZtM
package main
import (
"fmt"
)
func main() {
numbers := make(chan int)
go func() {
for i := 0; i < 100; i++ {
numbers <- i
}
close(numbers)
}()
for n := range numbers {
fmt.Println(n)
}
}
3 Likes
When main() ends, the whole program stops, even if a running goroutine hasn’t completed.
Add wait logic like this:
https://goinbigdata.com/golang-wait-for-all-goroutines-to-finish/
All your concurrency questions answer is this absolutely FABULOUS book:
Concurrency in Go
by Katherine Cox-Buday
Released August 2017
Publisher(s): O’Reilly Media, Inc.
ISBN: 9781491941294
Don’t hesitate. Just buy the book, and read it. You will be glad you did.
Good luck.
Jeff Kayser
1 Like