douyou2732 2016-03-05 08:31
浏览 36
已采纳

Golang变量中两个持续时间的乘积为零

It's weird in below Golang code that product of two time duration is zero in variable 'delay', but when print the product directly without through any variable, the output is as expected. Anyone can explain this?

 func StartCleanTask() {
  go func() {
       delay := cfg.Config.Timeout * time.Second
       for {
           fmt.Println("Go clean task: ", delay, cfg.Config.Timeout*time.Second)
           select {
           case <-time.After(cfg.Config.Timeout * time.Second):
               clean()
           }
     }
  }()

}

The output is:

 Go clean task: 0 5m0s

Update:

I also attempted to run following code, it works well.

package main 
import "fmt"
import "time"

func main() {

   var timeout time.Duration
   timeout = 100
   delay := timeout * time.Second

   fmt.Println("Go clean task: ", delay, timeout*time.Second)

}

Update again:

Paul's answer is accepted. Actually StartCleanTask() is invoked in the init function of cfg package, and cfg.Config.Timeout is assigned to a specified value in main function. BUT I ignored that package's init() function is invoked implicitly before main(), so the variable delay is always ZERO.

BTW, I don't understand why some people give negative score to this question. I think others may hit similar problem, and this post should be helpful to the victim who don't really know the calling sequence between init() and main().

  • 写回答

1条回答 默认 最新

  • dsk95913 2016-03-05 12:45
    关注

    My guess is that you're updating cfg.Config.Timeout concurrently to this task. Perhaps like this:

    func main() {
        StartCleanTask()
        cfg.Config.Timeout = 300
        ...
    }
    

    This introduces a race, and it happens that in the goroutine inside StartCleanTask, delay is assigned before the Timeout is initialized, and the fmt.Println happens after the initialization.

    You can use the race detector to see if this is the problem.

    Assuming that cfg is only initialized once, probably the right fix is to only start the cleanup task once the initialization has finished.

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

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂