首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >同步游戏中的go例程

同步游戏中的go例程
EN

Stack Overflow用户
提问于 2021-03-15 10:52:34
回答 1查看 55关注 0票数 0

我是一个全新的人,我正在尝试将游戏编码为一个练习。

基本上,主流将创建totalNumberOfPlayers例程,每个例程将执行一些任务后,一个圆形的游戏。在每一轮结束时,一名球员被从游戏中移除,直到只剩下一名玩家。

为了确保例程在同一轮中同步,我尝试使用WaitGroup,如下所示:

代码语言:javascript
运行
复制
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()
}

每个例程运行相同的任务:

代码语言:javascript
运行
复制
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()函数中创建另一个循环,我更希望避免这样做,以保留代码的结构。

EN

回答 1

Stack Overflow用户

发布于 2021-03-15 16:14:57

你似乎误解了sync.WaitGroup的用途。检查

一个WaitGroup在等待一组猩猩完成。

在使用sync.WaitGroup时,我建议您在使用go func()之前添加1,并在使用go func()之后将其添加延迟标记为finish。

假设您在main中使用go例程来调用routineJob。因此,您需要首先在这里添加sync.WaitGroup,让您的主等待全部完成。

代码语言:javascript
运行
复制
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例程,您可以按照上面的方式申请。

代码语言:javascript
运行
复制
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
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66636566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档