dongyuan7110 2013-11-07 21:59
浏览 72
已采纳

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"
        }
    }
}
  • 写回答

1条回答 默认 最新

  • doufangyan6862 2014-02-09 10:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大