When the tick is received, you send 3 on channel c and immediately close c
and reach the end of your program while the go routine runs. So you have no
guarantee that the program won't terminate before the go routine completes,
which is what happens here.
I'm new to go so this may not be the best ways, but I think you can either
(1) define another completion channel on which the go routine will send a
message and make the program wait for the message or (2) use sync.WaitGroup
as follows:
import (
//...
"sync"
)
func main() {
var w sync.WaitGroup
w.Add(1)
//...
go func(c chan int) {
//...
w.Done()
}(c)
//...
select {
//...
}
w.Wait()
}
Note that the sync group's Add() must be done before the go routine is
started.
Le samedi 7 mars 2015 11:03:34 UTC+1, Chakib Benziane a écrit :
I am trying to understand go channels/select. This is a modification of
the go tour chapter about buffered channel creation.
I want this code to produce the output:
1
2
3
quit
But I am getting this instead
1
2
quit
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int, 3)
c <- 1
c <- 2
tick := time.Tick(2000 * time.Millisecond)
go func(c chan int) {
for v := range c {
fmt.Println(v)
}
fmt.Println("quit")
}(c)
select {
case <-tick:
c <- 3
close(c)
}
}
Thanks for your help and remarks
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.