doushi6932 2018-09-30 03:35
浏览 10
已采纳

在go例程中更新后不返回更新后的值

I am running into a problem where integer value being returned is same as the one set, even after the value is updated in a go subroutine. I cannot seem to figure out whats wrong.

//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
", 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
", hurp.uptime)
    time.Sleep(3*time.Second)
    fmt.Printf("new uptime:%v
", hurp.uptime)

}

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

Any pointers are appreciated.

Thanks!

  • 写回答

1条回答 默认 最新

  • dqc18251 2018-09-30 04:03
    关注

    The function that launches the goroutine returns a HostUptimeReporter:

    func NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter {
    

    Returning a whole struct like that returns a copy of the struct so the goroutine and the NewHostUpTimeReporter caller are looking at different things. You want to return a pointer so they're sharing data:

    // -----------------------------------------------------v
    func NewHostUpTimeReporter(updateIntervalInSeconds int) *HostUptimeReporter {
        instance := &HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59}
        // ---------^
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码