多 Go-Routine 循环未按预期执行

Multi Go-Routine Loop Not Executing as Expected

**编辑更简洁明了

我对 Go 相当陌生,对 GoRoutines 绝对陌生,但我需要为我正在构建的程序添加一定程度的并发性。

我想要做的是同时 go func 运行ning,从技术上讲,它们是。然而,他们也不是 运行ning 我所期望的那样。

顶部go func 应该运行 每五秒寻找一个新工作和一个打开设备到运行 工作。如果有新作业,它会检查打开的设备。假设有三个新作业和两个打开的设备,for _, device := range 循环应该 运行 两次将每个作业分配给一个设备。五秒钟后,循环将再次 运行 并查看是否还有一项作业待 运行,并检查这些设备是否对 运行 该作业开放。 同时,我希望 subSSH 函数被连续调用。

实际发生的是设备每五秒只循环 运行s 一次,所以它只需要第一个设备和 运行s 代码,然后它等待五秒钟并执行第二份工作也是如此,然后是第三份工作,从不使用第二个设备或 运行 循环两次。

go func() {
    for {
        duration := 5 * time.Second
        for x := range time.Tick(duration) {//this loop runs every five seconds
            newJobs := checkForNew(jobcoll)
            if len(newJobs) != 0 {
                openPool := checkPoolDeviceStatus(poolcoll)
                for _, device := range openDevices {
                    //for each open device this loop should run once

                }
            }
        }
    }
}()

go func() {
    subSSH(subChannel, jobcoll, poolcoll)
}()

我已经尝试添加等待组并添加新的等待新作业的数量,但这导致设备循环根本无法执行。

我想我在这里遗漏了一些明显的东西,非常感谢您的帮助! 谢谢!

你的代码走在正确的道路上,但你的变量在错误的范围内。您还有一个嵌套的 for 循环,所以请继续并删除它。

你会想要这样的东西:

go func() {
    ticker := time.NewTicker(5 * time.Second) // setup outside the loop.
    for t := range ticker.C { // every time 5 seconds passes, this channel will fire.
        newJobs := checkForNew(jobcoll)
        if len(newJobs) != 0 {
            openPool := checkPoolDeviceStatus(poolcoll)
            for _, device := range openDevices {
                // the thing should occur.
            }
        }
    }
}()

这应该可以解决问题。参见:https://play.golang.org/p/zj6jdoduCcp

如果你想要一个连续执行的 goroutine,你需要一个连续的循环。

// only executes once and quits.
go func() { doTheThing() }()

// executes continuously after each execution exit.
go func() { for { doTheThing() } }()

// "background" function
go func() { doTheThingThatNeverExits() }()

goroutine 被设计为后台进程(过于简单化)。 goroutine 只是一个易于使用的包装器,用于在调用函数时轻松并发。

编辑:遗漏了最后一点。