gpt4 book ai didi

go - len() 线程在 golang 中安全吗?

转载 作者:IT王子 更新时间:2023-10-29 01:44:04 26 4
gpt4 key购买 nike

我每秒记录一张 map 的长度;我不在乎我是否具有“精确”值/竞争条件(差一个就可以)。我很想知道这是否会导致 panic ,以及我是否必须len() 与一些 .RLock()/Unlock() 或不。

我问是因为 ma​​p 中的并发读/写会导致 panic (Go 检测到)但我不知道读取长度是否算作“读取”。我已经尝试使用测试程序但无法产生崩溃,但我宁愿有一个确切的答案,至少为了它。

如果重要的话,我对数组和映射的 len 都感兴趣。谢谢!

最佳答案

这是一个竞争条件。结果未定义。例如,

racer.go:

package main

func main() {
m := make(map[int]int)
l := 0
go func() {
for {
l = len(m)
}
}()
for i := 0; i < 10000; i++ {
m[i] = i
}
}

输出:

$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00c00008e000 by goroutine 5:
main.main.func1()
/home/peter/gopath/src/racer.go:8 +0x5f

Previous write at 0x00c00008e000 by main goroutine:
runtime.mapassign_fast64()
/home/peter/go/src/runtime/map_fast64.go:92 +0x0
main.main()
/home/peter/gopath/src/racer.go:12 +0xba

Goroutine 5 (running) created at:
main.main()
/home/peter/gopath/src/racer.go:6 +0x92
==================
Found 1 data race(s)
exit status 66
$

引用资料:

Wikipedia: Race condition

The Go Blog: Introducing the Go Race Detector

Go: Data Race Detector

Benign Data Races: What Could Possibly Go Wrong?

关于go - len() 线程在 golang 中安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710882/

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