gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:09:25 25 4
gpt4 key购买 nike

**编辑更简洁明了

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

我想要做的是让 go func 同时运行,从技术上讲,它们是。然而,它们并没有像我期望的那样运行。

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

实际发生的是设备循环每五秒只运行一次,所以它只需要第一个设备并运行代码,然后它等待五秒钟并对第二个作业执行相同的操作,然后是第三个作业,永远不要使用第二个设备或运行该循环两次。

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)
}()

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

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

最佳答案

您的代码走在正确的道路上,但您的变量在错误的范围内。您还有一个嵌套的 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 只是一个易于使用的包装器,用于在调用函数时轻松并发。

编辑:错过了最后一点。

关于go - 多 Go-Routine 循环未按预期执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54356888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com