how to use go channel to handle 2 process concurrently

huangapple go评论80阅读模式
英文:

how to use go channel to handle 2 process concurrently

问题

以下是翻译好的内容:

这里有两个方法的流程如下。首先,在method01中按顺序获取4个批次的列表,每个批次列表的起始ID是前一个批次的最后ID。之后,我想要使用Go通道并发运行method02来处理每个结果批次,如何编写以实现高可用性?

for 0 range 3:{
    list := method01(id, limit)
    id := list[len(list) - 1].getId()
}
// 对于上述每个批次列表,使用并发方式执行method02
method02(list)
英文:

here's 2 method processes as below. firstly get 4 batches list in method01 in order, start_id of each batch list is the last_id of previous batch. after that, I wanna concurrently run method02 for each result batch by using go channel, how to write it high availability

for 0 range 3:{
    list := method01(id, limit)
    id := list[len(list) - 1].getId()
}
// for each above batch list, do method02 concurrently
method02(list)

答案1

得分: 2

for i := 0; i < 3; i++ {
    list := method01(id, limit)
    id := list[len(list)-1].getId()
    // 对于每个批次的列表,使用并发方式执行 method02
    go method02(list)
}

go 关键字是使函数并发执行的关键。你可以在 go tour 页面 上了解更多信息。我还建议使用类似 sync.WaitGroup 的东西,这样你可以等待进程完成。

英文:
for i:=0; i &lt; 3; i++ {
    list := method01(id, limit)
    id := list[len(list) - 1].getId()
    // for each above batch list, do method02 concurrently
    go method02(list)
}

go keyword is all you need to make the function concurrent. You can learn more at go tour page. I also would suggest to use something like sync.WaitGroup so you can wait for your processes to finish.

huangapple
  • 本文由 发表于 2021年8月3日 20:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/68636504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定