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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)