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!