英文:
Go maps fails the concurency test
问题
当我运行以下代码时:
import (
"log"
"sync"
"testing"
"time"
)
func TestConcurrency(t *testing.T) {
var mutex sync.RWMutex
dictionary := make(map[interface{}]interface{})
go func() {
var value interface{}
for {
go func() {
mutex.Lock()
dictionary["Key"] = ""
mutex.Unlock()
}()
go func() {
mutex.RLock()
value = dictionary["Key"]
mutex.RUnlock()
}()
}
log.Println(value)
}()
}
使用:
go test -race fileName.go
结果是:
发现1个数据竞争
我该如何解决这个问题?
我有很多并发的写入和读取操作。
英文:
When I run the following code:
import (
"log"
"sync"
"testing"
"time"
)
func TestConcurrency(t *testing.T) {
var mutex sync.RWMutex
dictionary := make(map[interface{}]interface{})
go func() {
var value interface{}
for {
go func() {
mutex.Lock()
dictionary["Key"] = ""
mutex.Unlock()
}()
go func() {
mutex.RLock()
value = dictionary["Key"]
mutex.RUnlock()
}()
}
log.Println(value)
}()
}
using :
go test -race fileName.go
It results in:
Found 1 data race(s)
How can I solve this?
I have many concurrent writes and reads.
答案1
得分: 4
如果你查看竞争检测器报告的错误,你会发现它报告了在value = dictionary["Key"]
这一行上的并发写操作,这意味着检测到的竞争是在value
而不是dictionary
上。
你同时访问了两个变量,dictionary
和value
。你不能使用读锁来保护对映射的读取和对value
变量的写入。你要么需要第二个互斥锁,要么需要始终使用mutex.Lock
来串行访问这两个变量。
英文:
If you look at the error presented by the race detector, you would see that it reported concurrent writes on the value = dictionary["Key"]
line, meaning the race being detected is on value
, not dictionary
.
You are concurrently accessing 2 variables, dictionary
and value
. You can't use the read lock to protect reads on the map, and writes to the value
variable. You either need a second mutex, or you need to always use mutex.Lock
to serialize access to both variables.
答案2
得分: 0
这段代码将正常工作:
go func() {
mutex.Lock()
value = dictionary["Key"]
mutex.Unlock()
}()
它保护变量value免受并发写入的影响。
英文:
This code will work correctly:
go func() {
mutex.Lock()
value = dictionary["Key"]
mutex.Unlock()
}()
It protects the variable value from concurrent write.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论