Multithreading go例程中更新后未返回更新值
我遇到了一个问题,返回的整数值与设置的整数值相同,即使在go子例程中更新了整数值。我似乎不知道出了什么问题Multithreading go例程中更新后未返回更新值,multithreading,go,subroutine,Multithreading,Go,Subroutine,我遇到了一个问题,返回的整数值与设置的整数值相同,即使在go子例程中更新了整数值。我似乎不知道出了什么问题 //HostUptimeReporter - struct type HostUptimeReporter struct { updateInterval int uptime int shutdownSignal chan bool } //NewHostUpTimeReporter - create reporter instance func NewHos
//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)
}
//HostUptimeReporter-struct
类型HostUptimeReporter结构{
更新区间整数
正常运行时间
关闭信号chan bool
}
//NewHostUpTimeReporter-创建报告器实例
func NewHostUpTimeReporter(updateIntervalinsSeconds int)HostUptimeReporter{
实例:=HostUptimeReporter{updateInterval:updateIntervalInSeconds,ShutdowSignal:make(chan bool),正常运行时间:59}
ticker:=time.NewTicker(time.Duration(updateIntervalInSeconds)*time.Second)
go func(){
为了{
挑选{
case启动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}
// ---------^
...
启动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}
// ---------^
...