var loggers []*logOutput = nil
func init() {
loggers = make([]*logOutput, int(LOGGER_USAGE_TYPE_COUNT))
}
func ABC() {
loggers[loggerType].ticker = time.NewTicker(time.Second *
time.Duration(logRotateCheckInterval))
go func() {
defer RecoverFunc()
for {
<-loggers[loggerType].ticker.C
loggers[loggerType].checkAndRotateLogFile()
}
}()
}
<-loggers[loggerType].ticker.C
will sometimes panic. And there's only one goroutine modifying loggers[loggerType]
and loggers[loggerType].ticker
. I found that when panic happens, loggers[loggerType].ticker
is nil
, which makes me feel that the goroutine use the value of loggers[loggerType].ticker
before loggers[loggerType].ticker = time.NewTicker(time.Second * time.Duration(logRotateCheckInterval))
is executed.
Could anyone explain when the closure takes the value of a outside variable? I change the logger as a pointer variable to the goroutine func as a solution