我有一个循环,我收到此错误,我正在运行go run -race main.go
这是有问题的循环:
var wg sync.WaitGroup
for _, member := range p.Members { << Line 254
go func() {
wg.Add(1)
_, err := db.Exec("UPDATE party_members SET active = ? WHERE steamid = ?", false, member.SteamID) << Line 257
if err != nil {
log.Println(err)
}
_, err = db.Exec("INSERT INTO party_members SET belongs_to =?, active = ?, steamid = ?", partyUUID, true, member.SteamID)
if err != nil {
log.Println(err)
}
wg.Done()
}() << Line 266
}
然后这是我得到的错误:
WARNING: DATA RACE
Read by goroutine 44:
BLAH/controllers/partybot.func·001()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:257 +0x136
Previous write by goroutine 43:
BLAH/controllers/partybot.(*PartialParty).SendReadyCheck()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:254 +0xda5
Goroutine 44 (running) created at:
BLAH/controllers/partybot.(*PartialParty).SendReadyCheck()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:266 +0xf13
Goroutine 43 (finished) created at:
BLAH/controllers/partybot.(*PartyHub).SortMemberIntoParty()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:173 +0xdb9
BLAH/controllers/partybot.(*Connection).readPump()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:359 +0x1872
BLAH/controllers/partybot.WSPartyBot()
/Users/Dev/gocode/src/BLAH/controllers/partybot/partybot.go:440 +0x4f0
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:1265 +0x4e
github.com/gorilla/mux.(*Router).ServeHTTP()
/Users/Dev/gocode/src/github.com/gorilla/mux/mux.go:98 +0x377
BLAH/controllers/common.func·001()
/Users/Dev/gocode/src/BLAH/controllers/common/common.go:36 +0xc2
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:1265 +0x4e
net/http.(*ServeMux).ServeHTTP()
/usr/local/go/src/net/http/server.go:1541 +0x20c
net/http.serverHandler.ServeHTTP()
/usr/local/go/src/net/http/server.go:1703 +0x1f6
net/http.(*conn).serve()
/usr/local/go/src/net/http/server.go:1204 +0x1087
==================
我不确定为什么这是一场数据竞赛,因为如果有人能告诉我为什么这会很好的话,我对Go来说还是一个新手,我标记了有问题的行。
答案 0 :(得分:6)
问题是goroutine正在访问变量&#39;成员&#39;通过闭包,在go中,这个引用在到达时被评估(即它看到了goroutine执行时的成员值,而不是通过go func()... call创建它的成员变量。循环更新,所以在循环更新和你已经开始阅读它们的goroutines之间有一场竞赛。(如果你进一步挖掘你的数据库没有看到确切的数据,你会发现集合中的成员集。通常,您可以通过在循环中强制评估变量来解决此问题,方法是创建局部变量,或者将其作为参数添加到func中,例如
var wg sync.WaitGroup
for _, member := range p.Members {
wg.Add(1)
m := member
go func() {
_, err := db.Exec("UPDATE party_members SET active = ? WHERE steamid = ?", false, m.SteamID)
...
wg.Done()
}()
}
或
var wg sync.WaitGroup
for _, member := range p.Members {
wg.Add(1)
go func(m memberType) {
_, err := db.Exec("UPDATE party_members SET active = ? WHERE steamid = ?", false, m.SteamID)
...
wg.Done()
}(member)
}
还要注意,你需要从循环中调用wg.Add(1),而不是从goroutine本身调用。