I run a goroutine to increment a counter, which can be interrupted by command line input "t "
In the select
statement, if I choose to use default:
, the counter variable j
flies forword. That seems normal to me.
However, if I choose to use case <-time.After(100*time.Microsecond):
, the counter j
only adds up to 60 or so in one second, instead of 10,000.
In fact no matter what value I put in time.After()
, I only get about 60Hz rate running through the select
statement.
Why?
package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
func main() {
message := make(chan string)
go check_input(message)
work_loop(message)
}
func work_loop(message chan string) {
//var j [][]int
var j int
t0:=time.Now()
Loop:
for {
select {
case msg := <-message:
if msg == "terminate" {
//fmt.Println("end task")
t1:=time.Now()
fmt.Println(j)
fmt.Println("total duration:", t1.Sub(t0))
break Loop
}
case <-time.After(100 * time.Microsecond):
//default:
//do work here
j += 1
fmt.Println(j)
break
}
}
//fmt.Println("exit work loop")
}
func check_input(msg chan string) {
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('
')
if err != nil {
// You may check here if err == io.EOF
break
}
if strings.TrimSpace(line) == "t" {
msg <- "terminate"
}
}
}