我是一个全新的人,我正在尝试将游戏编码为一个练习。
基本上,主流将创建totalNumberOfPlayers例程,每个例程将执行一些任务后,一个圆形的游戏。在每一轮结束时,一名球员被从游戏中移除,直到只剩下一名玩家。
为了确保例程在同一轮中同步,我尝试使用WaitGroup,如下所示:
func main() {
// ... initialization code
var wg sync.WaitGroup
for i := 0; i < totalNumberOfPlayers; i++ {
go routineJob(i, ..., &wg)
}
// TODO Temporary workaround to let the main flux wait
fmt.Scanln()
}每个例程运行相同的任务:
func routineJob(routineId int, ..., wg *sync.WaitGroup) {
// ...
for round := 0; round < totalNumberOfPlayers-1; round++ {
numberOfPlayers := totalNumberOfPlayers - round
wg.Add(1) // Add player to round
// ... perform some tasks
if ... { // Player verifies condition to be removed from the game
wg.Done() // Remove player from round
return
}
// ... perform some other tasks
wg.Done() // Remove player from round
wg.Wait() // Wait for all players to be removed before going to the next round
}
}但在第一轮结束时,我得到了以下错误:
WaitGroup :在前一次等待返回之前被重用
环顾在线,我发现问题可能是,在打电话给wg.Wait()之后,我不允许打电话给wg.Add(1)。如果是这样的话,如何实现这样一个基于回合的游戏?
备注:--我想为每一轮创建一个外部WaitGroup,但这需要我在main()函数中创建另一个循环,我更希望避免这样做,以保留代码的结构。
发布于 2021-03-15 16:14:57
你似乎误解了sync.WaitGroup的用途。检查这
一个WaitGroup在等待一组猩猩完成。
在使用sync.WaitGroup时,我建议您在使用go func()之前添加1,并在使用go func()之后将其添加延迟标记为finish。
假设您在main中使用go例程来调用routineJob。因此,您需要首先在这里添加sync.WaitGroup,让您的主等待全部完成。
func main() {
// ... initialization code
var wg sync.WaitGroup
for i := 0; i < totalNumberOfPlayers; i++ {
wg.Add(1)
go func(){
// we add 1 for each loop and when the job finish, defer will run which mark added one done.
defer wg.Done()
routineJob(i, ...)
}()
}
wg.Wait()
// no need your work around any more.
fmt.Scanln()为了你的routineJob。如果有任何想要等待的go例程,您可以按照上面的方式申请。
func routineJob(routineId int, ...) {
for round := 0; round < totalNumberOfPlayers-1; round++ {
var wg sync.WaitGroup // I assume that you need a list of funcs running in go routine here.
wg.Add(1)
go func() {
defer wg.Done()
// Do your logic....
return
}()
// your go routine 2
wg.Add(1)
go func() {
defer wg.Done()
// Do your logic....
return
}()
wg.Wait() // Wait for all players to be removed before going to the next roundx
}
}https://stackoverflow.com/questions/66636566
复制相似问题