登录
首页 >  Golang >  Go问答

恢复 goroutine 工作的最佳方式是什么

来源:stackoverflow

时间:2024-04-12 12:27:35 374浏览 收藏

本篇文章给大家分享《恢复 goroutine 工作的最佳方式是什么》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我必须使用某些远程服务器上可用的数据更新数千个结构。因此,我必须处理数千个 goroutines 查询这些远程服务器(http 请求或 db 请求),以使用响应更新结构。但该结构体的更新(或不更新)取决于其他结构体的结果。

所以我想象了一个简单的代码,其中 goroutine 运行,每个 goroutine 执行自己的请求,将结果放入一个全局结构中,其中包含 goroutine 检索到的任何信息,并通知 main func工作已完成(在决定更新或不更新其结构之前,等待每个 goroutine 执行相同操作的信号。)

goroutine 现在应该等待主线程发出所有 goroutine 都已完成的信号,然后再决定是否更新

简化的代码如下所示:

type struct structtoupdate {
  //some properties
}

type struct globalwatcher {
  //some userful informations for all structs to update (or not)
}

func main() {
  //retrieving all structs to update
  structstoupdates := foo() 

  //launching goroutines
  c := make(chan bool)
  for _,structtoupdate := range structstoupdates {
    go updatestruct(&structtoupdate,c)
  }

  //waiting for all goroutines do their first part of job
  for i:=0; i

问题是:更高效/惯用/优雅的等待是什么:

  • 从主脚本发送信号?
  • 等待来自 goroutine 的信号?

我可以想象 3 种方法来做到这一点

  • 在第一种方式中,我可以想象一个全局 bool var resume := false ,当所有 goroutine 完成第一部分工作时,主函数将把它转换为 true 。在这种情况下,每个 goroutine 都可以使用丑陋的 for !resume { continue }....
  • 在更惯用的代码中,我可以想象做同样的事情,但我可以使用 context.withvalue(ctx, "resume", false) 并将其传递给 goroutine,而不是使用 bool,但我仍然有a for !ctx.value("resume")
  • 在最后一个更优雅的代码中,我可以想象使用另一个传递给 goroutine 的 resume := make(chan bool) 。 main func 可以通过简单的 close(resume) 通知 goroutine 恢复关闭此 chan。 goroutine 将等待信号,其内容如下:
for {
  _, more := <-resume
  if !more {
    break
  }
}
//update or not

还有其他好主意吗?上述解决方案之一比其他解决方案更好?


正确答案


我不确定我是否完全理解你的问题,但阻塞主线程的一个简单解决方案是使用操作系统信号,即:

done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGTERM)

// Blocks main thread
<-done

这不一定是操作系统信号,这可能是从运行时其他位置接收 struct{}{} 值的通道。

如果您由于多个 go 例程工作而需要执行此操作,我会考虑使用 sync.waitgroup

以上就是《恢复 goroutine 工作的最佳方式是什么》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>