当前位置: > > > > 在回合游戏中同步 Go 例程
在回合游戏中同步 Go 例程
来源:stackoverflow
2024-04-26 13:00:37
0浏览
收藏
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《在回合游戏中同步 Go 例程》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
问题内容
我对 go 完全陌生,我正在尝试编写一个游戏作为练习。
基本上,主流程将创建 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
}
}
但是在第一轮结束时我收到以下错误:
恐慌:同步:在先前的等待返回之前重用等待组
在网上查了一下,我发现问题可能是在调用 wg.wait() 之后,我不允许调用 wg.add(1)。如果是这样的话,如何实现这样的基于回合的游戏?
注意:我正在考虑为每一轮创建一个外部 waitgroup ,但这需要我在 main() 函数中以某种方式创建另一个循环,我宁愿避免这种情况以保留代码的结构大部分如所呈现的那样。
解决方案
您似乎误解了sync.waitgroup的用途。检查
使用sync.waitgroup时,我建议您在使用go func()之前添加1,并在使用go func()之后添加defer以将其标记为完成。
假设您在 main 中使用 go 例程来调用 routinejob。所以你需要先在这里添加sync.waitgroup,让你的main等待所有goroutine完成。
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()
适合您的日常工作。如果有需要等待的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
}
}
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
