函数传递了奇怪的变量?time.Minute没有作为分钟传递。

huangapple go评论64阅读模式
英文:

Strange variable passed to function? time.Minute not being passed as a minute

问题

我有一个函数:

func myFunc(mycontext context.Context, duration time.Duration, f someFunc) {
    for {
        select {
        case <-time.After(duration):
            // 做一些事情
        case <-mycontext.Done():
            // 其他事情
        }
    }
}

这样调用:

duration := time.Minute
go myFunc(mycontext, duration, myFuncPointer)

今天我注意到这个函数永远不会退出。在暂停和检查go线程时,我发现我的duration变量具有以下值:

github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)

为什么它具有这个值而不是我设置的一分钟的持续时间?而且duration在任何时候都没有重新赋值,所以我认为不是这个问题。

英文:

I have a function that is

func myFunc(mycontext context.Context, duration time.Duration, f someFunc) {
for {
   select {
      case &lt;- time.After(duration):
          // do some stuff
      case &lt;-mycontext.Done():
          // Other stuff
   }
}

This is called with

duration := time.Minute
go myFunc(mycontext, duration, myFuncPointer)

Today I noticed this function never exits. Upon pausing and inspecting the gothread I see that my duration variable has this value

github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)

Why does it have this value and not my one minute duration? Also duration never gets reassigned at any point so I don't think its that.

答案1

得分: 3

我看到我的持续时间变量具有这个值

github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)

为什么它具有这个值而不是我的一分钟持续时间?

阅读Go标准库time包的文档。

type Duration int64

Duration表示两个时刻之间经过的时间,以int64纳秒计数。

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

time.Minute60000000000纳秒。

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(int64(time.Minute))
}

https://go.dev/play/p/YVx4ddJYnv6

60000000000
英文:

> I see that my duration variable has this value
>
> github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)
>
> Why does it have this value and not my one minute duration?


Read the Go standard library package time documentation.

> type Duration int64
>
> A Duration represents the elapsed time between two instants as an int64 nanosecond count.

> const (
> Nanosecond Duration = 1
> Microsecond = 1000 * Nanosecond
> Millisecond = 1000 * Microsecond
> Second = 1000 * Millisecond
> Minute = 60 * Second
> Hour = 60 * Minute
> )


time.Minute is 60000000000 nanoseconds.

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	fmt.Println(int64(time.Minute))
}

https://go.dev/play/p/YVx4ddJYnv6

60000000000

huangapple
  • 本文由 发表于 2023年7月18日 08:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定