英文:
Golang how can I guarantee data finishes in a goroutine while being accessed by another goroutine
问题
大家好,我正在尝试使用Websockets创建一个派对系统,人们可以进入队列,然后与5个与他们相似的人匹配。目前我在以下部分遇到了问题:
type PartyHub struct {
Partys map[string]*Party
PartialPartys []*PartialParty
Queue []*Member
AddParty chan *Party
RemoveParty chan *Party
AddPartialParty chan *PartialParty
RemovePartialParty chan *PartialParty
EnterQueue chan *Member
LeaveQueue chan *Member
Mu sync.Mutex
}
func (p *PartyHub) Run() {
for {
select {
case member := <-p.EnterQueue:
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
log.Println(p.PartialPartys)
case party := <-p.AddPartialParty:
p.Mu.Lock()
defer p.Mu.Unlock()
p.PartialPartys = append(p.PartialPartys, party)
}
}
}
func (p *PartyHub) SortMemberIntoParty(member *Member) {
p.Mu.Lock()
defer p.Mu.Unlock()
if len(p.PartialPartys) == 0 {
log.Println("Here")
newParty := &PartialParty{Accepting: true, Members: []*Member{member}}
p.AddPartialParty <- newParty
return
}
foundPartyForMember := false
for _, party := range p.PartialPartys {
goodFitForParty := true
for _, partyMember := range party.Members {
log.Println(member.Type == partyMember.Type, member.Rank >= partyMember.Rank-partyMember.RankTol, member.Rank <= partyMember.Rank+partyMember.RankTol)
if member.Type == partyMember.Type && member.Rank >= partyMember.Rank-partyMember.RankTol && member.Rank <= partyMember.Rank+partyMember.RankTol {
goodFitForParty = true
continue
} else {
goodFitForParty = false
break
}
}
if !goodFitForParty {
continue
} else {
foundPartyForMember = true
party.Mu.Lock()
defer party.Mu.Unlock()
party.Members = append(party.Members, member)
if len(party.Members) == 5 {
party.Accepting = false
go party.SendReadyCheck()
}
break
}
}
if !foundPartyForMember {
newParty := &PartialParty{Accepting: true, Members: []*Member{member}}
p.AddPartialParty <- newParty
}
log.Println("Sorting Members")
}
唯一的问题是,这5个goroutine
似乎比数据更快地完成了操作。
例如:p.PartialPartys
显示没有派对。
我需要的是,对于每个访问PartyHub
结构体的goroutine
,p.PartialPartys
始终保持最新状态。我以为sync.Mutex
会为我完成这个工作,但似乎并不是这样。有人能告诉我保持所有goroutine
与相同数据同步的最佳方法吗?
英文:
Hi guys I am trying to make a party system using websockets where people can enter a queue and then get matched with 5 people similar to them. Right now I'm having trouble with this part:
type PartyHub struct {
Partys map[string]*Party
PartialPartys []*PartialParty
Queue []*Member
AddParty chan *Party
RemoveParty chan *Party
AddPartialParty chan *PartialParty
RemovePartialParty chan *PartialParty
EnterQueue chan *Member
LeaveQueue chan *Member
Mu sync.Mutex
}
// Run will begin monitoring the channels
// to register and unregister partys as they are
// created or destroyed
func (p *PartyHub) Run() {
for {
select {
case member := <-p.EnterQueue:
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
go p.SortMemberIntoParty(member)
log.Println(p.PartialPartys)
case party := <-p.AddPartialParty:
p.Mu.Lock()
defer p.Mu.Unlock()
p.PartialPartys = append(p.PartialPartys, party)
}
}
}
// SortMemberIntoParty will take a new user entering the queue and find an appropriate Party
// for the member to join, taking into account RankTollerance, Rank
func (p *PartyHub) SortMemberIntoParty(member *Member) {
p.Mu.Lock()
defer p.Mu.Unlock()
if len(p.PartialPartys) == 0 {
log.Println("Here")
newParty := &PartialParty{Accepting: true, Members: []*Member{member}}
p.AddPartialParty <- newParty
return
}
foundPartyForMember := false
for _, party := range p.PartialPartys {
goodFitForParty := true
for _, partyMember := range party.Members {
log.Println(member.Type == partyMember.Type, member.Rank >= partyMember.Rank-partyMember.RankTol, member.Rank <= partyMember.Rank+partyMember.RankTol)
if member.Type == partyMember.Type && member.Rank >= partyMember.Rank-partyMember.RankTol && member.Rank <= partyMember.Rank+partyMember.RankTol {
goodFitForParty = true
continue
} else {
goodFitForParty = false
break
}
}
if !goodFitForParty {
continue
} else {
foundPartyForMember = true
party.Mu.Lock()
defer party.Mu.Unlock()
party.Members = append(party.Members, member)
if len(party.Members) == 5 {
party.Accepting = false
go party.SendReadyCheck()
}
break
}
}
if !foundPartyForMember {
newParty := &PartialParty{Accepting: true, Members: []*Member{member}}
p.AddPartialParty <- newParty
}
log.Println("Sorting Members")
}
The only problem is, the 5 goroutines
seem to finish quicker than the data knows what happened.
For example: p.PartialPartys
says it has no parties.
What I need is to have p.PartialPartys
always up to date for every goroutine
that accesses that field of the PartyHub
struct I though the sync.Mutex
would do this for me but it doesn't seem to be the case, can anybody tell me the best way to keep all my goroutines in sync with the same data?
答案1
得分: 5
所以根据这个实现,你的五个goroutine都无法并行运行,因为它们都试图获取p.Mu
互斥锁。从你使用p.AddPartialParty
通道的方式来看,如果代码发生死锁,我也不会感到惊讶。
考虑以下事件序列:
- 其中一个
SortMemberIntoParty
goroutine开始运行并获取互斥锁。 - 它在
p.AddPartialParty
上发送一个值,被Run
接收。然后,Run
尝试获取互斥锁,因此阻塞。 - 原始的
SortMemberIntoParty
goroutine完成并释放互斥锁。 - 另一个
SortMemberIntoParty
goroutine获取互斥锁,并尝试向p.AddPartialParty
发送另一个值。 - 该goroutine被阻塞,因为没有人准备读取该值(
Run
仍在等待互斥锁,然后才能回到select
语句)。
现在你有一个被阻塞的goroutine持有一个被通道接收端需要的锁。还要注意,在(4)中,你看不到新的PartialParty
,因为Run
还没有来得及添加它。
如果确实需要互斥锁,那么直接让你的SortMemberIntoParty
goroutine直接更新p.PartialPartys
可能更容易,而不是使用通道:你已经知道没有其他人会同时访问该变量。
还值得记住的是,这个互斥锁实际上意味着所有的SortMemberIntoParty
goroutine将被串行化。如果你希望在这里使用goroutine实现并行性,那么互斥锁将破坏这一点。
英文:
So with this implementation, none of your five goroutines are going to be be able to run in parallel because they are all trying to acquite the p.Mu
mutex. And looking at the way you're using the p.AddPartialParty
channel, I wouldn't be surprised if the code can deadlock.
Consider the following sequence of events:
- One of the
SortMemberIntoParty
goroutines starts running and acquires the mutex. - It sends a value on
p.AddPartialParty
, which is received byRun
.Run
then tries to acquire the mutex, so blocks. - The original
SortMemberIntoParty
goroutine completes and releases the mutex. - A different
SortMemberIntoParty
goroutine acquires the mutex, and tries to send another value top.AddPartialParty
. - The goroutine blocks because there is no one ready to read the value (
Run
is still waiting on the mutex before it gets back to theselect
statement).
So now you've got a blocked goroutine holding a lock needed by the receiving end of the channel. Also note that at (4) you won't see the new PartialParty
because Run
hasn't managed to add it yet.
If you do need the mutex, then it might be easier to just have your SortMemberIntoParty
goroutine update p.PartialPartys
directly rather than using the channel: you already know that no one else will be accessing the variable concurrently.
It's also worth remembering that this mutex essentially means that all SortMemberIntoParty
goroutines will be serialised. If you were using goroutines in the hope of achieving parallelism here, the mutex defeats that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论