gpt4 book ai didi

go - 包 "fmt"运行时问题

转载 作者:行者123 更新时间:2023-12-01 22:34:53 25 4
gpt4 key购买 nike

我遇到了一个看起来很简单但我无法重现的问题,因此我无法解释。

这个问题发生在生产中,神秘的是它很少发生(这就是我无法重现它的原因),这可能是我无法举例说明的一个因素,但这里是上下文:

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
}()
}

panic 堆栈跟踪:
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

感谢您的时间,我希望有人可以向我解释什么是错的。

最佳答案

你在这里有一个数据竞赛:

    var Object interface{}
go func(Get *interface{}) {
*Get = <- MyChan
} (&Object)
for Object == nil {
time.Sleep(time.Nanosecond * 1)
}


写入变量 Object 的 goroutine这样做不使用锁:它从 channel 接收,当它得到一个值时,它把它写入 *Get在哪里 Get == &Object , 使其写入 Object 的接口(interface)值.

同时,运行 for 的 goroutine循环从 Object 读取,检查零。它在不使用锁的情况下读取,因此它可以读取部分写入的值。

实际发生的是,部分写入的值不是零,没有设置整个值。所以 for loop 停止循环,代码进入下一行:

    log.Println(fmt.Sprint(Object)) // Panic here from the fmt.Sprint() func


由于 Object只写了一部分,访问它的值会产生不可预知的结果——但在这种情况下,它会产生 panic 。 (特别是接口(interface)的 type 字段已经设置,但是 value 字段仍然为零。实际的 panic 来自 src/reflect/value.go 中的这一行:

               return *(*string)(v.ptr)


v.ptr未设置。)

目前尚不清楚为什么要记录该值,也不清楚为什么要使用共享内存进行通信,但是如果这样做,则需要锁定。不这样做通常更明智。另见 this answerExplain: Don't communicate by sharing memory; share memory by communicating .

(或者,更简单地说,为什么不直接使用 Object := <-MyChan 来代替整个 goroutine-and-spin?)

关于go - 包 "fmt"运行时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59820480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com