recently in learning golang, channel timeout here, want to try more than one program how to judge timeout, I wrote the code as follows:
opened 10 programs, it is strange why half of the normal output, half timeout, just a simple output within 1 second should be able to normal output ah, very questionable, I hope someone can explain.
package main
import (
"fmt"
"time"
)
func send(k int, ch chan int) {
ch <- k
}
func main() {
fmt.Println(time.Now().Unix())
ch := make(chan int)
timeout := make(chan bool)
for k := 0; k < 10; kPP {
go send(k, ch)
go func() {
time.Sleep(1 * time.Second)
timeout <- true
}()
}
for i := 0; i < 10; iPP {
select {
case <-ch:
fmt.Println("receive:", <-ch)
case <-timeout:
fmt.Println("timeout")
}
}
fmt.Println(time.Now().Unix())
}
/ *
1535507000
receive: 1
receive: 3
receive: 5
receive: 7
receive: 9
timeout
1535507001
* /