首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在go例程更新后未返回已更新的值。

在go例程更新后未返回已更新的值。
EN

Stack Overflow用户
提问于 2018-09-30 03:35:50
回答 1查看 34关注 0票数 0

我遇到了一个问题,即使在go子例程中更新了该值之后,返回的整数值也与一个集合相同。我好像搞不清出了什么问题。

代码语言:javascript
运行
复制
//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

任何指点都会受到赞赏。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-30 04:03:50

启动goroutine的函数返回一个HostUptimeReporter

代码语言:javascript
运行
复制
func NewHostUpTimeReporter(updateIntervalInSeconds int) HostUptimeReporter {

返回一个像这样的完整结构,返回一个结构的副本,因此goroutine和NewHostUpTimeReporter调用者正在查看不同的内容。您希望返回一个指针,以便它们共享数据:

代码语言:javascript
运行
复制
// -----------------------------------------------------v
func NewHostUpTimeReporter(updateIntervalInSeconds int) *HostUptimeReporter {
    instance := &HostUptimeReporter{updateInterval: updateIntervalInSeconds, shutdownSignal: make(chan bool), uptime:59}
    // ---------^
    ...
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52574401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档