【发布时间】:2020-05-06 07:07:36
【问题描述】:
我遇到了一个看似简单但我无法重现的问题,因此我无法解释。
这个问题在生产中出现,神秘的是它很少发生(这就是为什么我无法重现它),这可能是我无法举例说明的一个因素,但这里是上下文:
type MyType struct {
Field1 string
Field2 int
Field3 time.Time
Field4 []float64
// No pointers fields
}
func main() {
var MyChan = make(chan interface{})
go func() {
// This routine is reading and parsing messages from a WS dial and writing it in a channel
// There is 2 only possible answer in the channel : a string, or a "MyType" like (with more fields, but no pointers in)
var Object MyType
Object.Field1 = "test"
// ..
MyChan <- Object
}()
go func() {
// This routine is sending a message to a WS dial and wait for the answer in a channel fed by another routine :
var Object interface{}
go func(Get *interface{}) {
*Get = <- MyChan
} (&Object)
for Object == nil {
time.Sleep(time.Nanosecond * 1)
}
log.Println(fmt.Sprint(Object)) // Panic here from the fmt.Sprint() func
}()
}
紧急堆栈跟踪:
runtime error: invalid memory address or nil pointer dereference
panic(0x87a840, 0xd0ff40)
X:/Go/GoRoot/src/runtime/panic.go:522 +0x1b5
reflect.Value.String(0x85a060, 0x0, 0xb8, 0xc00001e500, 0xc0006f1a80)
X:/Go/GoRoot/src/reflect/value.go:1781 +0x45
fmt.(*pp).printValue(0xc006410f00, 0x85a060, 0x0, 0xb8, 0x76, 0x1)
X:/Go/GoRoot/src/fmt/print.go:747 +0x21c3
fmt.(*pp).printValue(0xc006410f00, 0x8ed5c0, 0x0, 0x99, 0x76, 0x0)
X:/Go/GoRoot/src/fmt/print.go:796 +0x1b52
fmt.(*pp).printArg(0xc006410f00, 0x8ed5c0, 0x0, 0x76)
X:/Go/GoRoot/src/fmt/print.go:702 +0x2ba
fmt.(*pp).doPrint(0xc006410f00, 0xc0006f22a0, 0x1, 0x1)
X:/Go/GoRoot/src/fmt/print.go:1147 +0xfd
fmt.Sprint(0xc0006f22a0, 0x1, 0x1, 0x0, 0x0)
X:/Go/GoRoot/src/fmt/print.go:250 +0x52
Go 版本:1.12.1 windows/amd64
感谢您抽出宝贵时间,希望有人能向我解释问题所在。
【问题讨论】:
-
分配给 *Get 之后立即针对 for 条件进行比赛。竞争条件使您的程序的行为未定义。