亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
慕碼人8056858 2023-04-17 15:00:35
我遇到了一個問題,即返回的整數值與一組相同,即使在 go 子例程中更新了值之后也是如此。我似乎無法弄清楚出了什么問題。//HostUptimeReporter - structtype HostUptimeReporter struct {    updateInterval int    uptime int    shutdownSignal chan bool}//NewHostUpTimeReporter - create reporter instancefunc 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 routinefunc (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任何指針表示贊賞。
查看完整描述

1 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

啟動 goroutine 的函數返回一個HostUptimeReporter:


func NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter {

像這樣返回一個完整的結構會返回該結構的副本,因此 goroutine 和調用NewHostUpTimeReporter者正在查看不同的東西。你想返回一個指針以便他們共享數據:


// -----------------------------------------------------v

func NewHostUpTimeReporter(updateIntervalInSeconds int) *HostUptimeReporter {

    instance := &HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59}

    // ---------^

    ...


查看完整回答
反對 回復 2023-04-17
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號