Google Go Goroutine的中断模式(速度问题)

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"
        }
    }
}

It has to do with the precision of time.Timer. Looking at the documentation of time.After:

[...] It is equivalent to NewTimer(d).C.

and the documentation of time.NewTimer:

NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

(emphasis mine)

The reason for this is that NewTimer delegates to a runtime (OS-dependent) timer,making the behavior of this timer dependent on the underlying OS (and the implementation of the Go integration).

In general, it is my experience that sub-millisecond granularity does not have good cross-platform support in any language, especially on Windows XP.