在 go 例程中更新后未返回更新值

Updated value not being returned after update in a go routine

我 运行 遇到一个问题,即返回的整数值与一组相同,即使在 go 子例程中更新了值之后也是如此。我似乎无法弄清楚出了什么问题。

//HostUptimeReporter - struct
type HostUptimeReporter struct {
    updateInterval int
    uptime int
    shutdownSignal chan bool

}

//NewHostUpTimeReporter - create reporter instance
func NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter {
    instance := HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59}
    ticker := time.NewTicker(time.Duration(updateIntervalInSeconds) * time.Second)
    go func() {
        for {
            select {
            case <-ticker.C:
                instance.uptime += updateIntervalInSeconds          
                fmt.Printf("updated uptime:%v\n", instance.uptime)
            case <-instance.shutdownSignal:
                ticker.Stop()
                return
            }
        }
    }()

    return instance
}

//Shutdown - shuts down the go routine
func (hupr *HostUptimeReporter) Shutdown(){
    hupr.shutdownSignal <- true
}

func main() {

    hurp := NewHostUpTimeReporter(2)
    defer hurp.Shutdown()
    fmt.Printf("current uptime:%v\n", hurp.uptime)
    time.Sleep(3*time.Second)
    fmt.Printf("new uptime:%v\n", hurp.uptime)

}

https://play.golang.org/p/ODjSBb0YugK

不胜感激。

谢谢!

启动 goroutine 的函数 returns a HostUptimeReporter:

func NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter {

返回整个结构 return 是结构的副本,因此 goroutine 和 NewHostUpTimeReporter 调用者正在查看不同的东西。您想要 return 一个指针以便他们共享数据:

// -----------------------------------------------------v
func NewHostUpTimeReporter(updateIntervalInSeconds int) *HostUptimeReporter {
    instance := &HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59}
    // ---------^
    ...