如何让Go通道工作者有不同的结果长度?
一分耕耘,一分收获!既然都打开这篇《如何让Go通道工作者有不同的结果长度?》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
问题内容我对 gobyexample 进行了一些编辑:
import (
"fmt"
"math/rand"
"time"
)
type demoresult struct {
name string
rate int
}
func random(min, max int) int {
rand.seed(time.now().utc().unixnano())
return rand.intn(max-min) + min
}
func worker(id int, jobs <-chan int, results chan<- demoresult) {
for j := range jobs {
fmt.println("worker", id, "started job", j)
time.sleep(time.second)
fmt.println("worker", id, "finished job", j)
myrand := random(1, 4)
if myrand == 2 {
results <- demoresult{name: "succ", rate: j}
}
// else {
// results <- demoresult{name: "failed", rate: 999}
// }
}
}
func main() {
const numjobs = 5
jobs := make(chan int, numjobs)
results := make(chan demoresult)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= numjobs; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= numjobs; a++ {
out := <-results
if out.name == "succ" {
fmt.printf("%v\n", out)
}
}
}
我故意对以下代码进行了注释,使其永远卡住:
// else {
// results <- DemoResult{Name: "failed", Rate: 999}
// }
看来我们应该使结果的长度与 jobs 的长度相同。我想知道我们是否可以使其具有不同的长度?
正确答案
使用 wait group 检测工作人员何时完成。当工作人员完成后,关闭结果通道。接收结果直到通道关闭。
func worker(wg *sync.waitgroup, id int,
jobs <-chan int,
results chan<- demoresult) {
// decrement wait group counter on return from
// function.
defer wg.done()
⋮
}
func main() {
⋮
// declare wait group and increment counter for
// each worker.
var wg sync.waitgroup
for w := 1; w <= 3; w++ {
wg.add(1)
go worker(&wg, w, jobs, results)
}
⋮
// wait for workers to decrement wait group
// counter to zero and close channel.
// execute in goroutine so we can continue on
// to receiving values from results in main.
go func() {
wg.wait()
close(results)
}()
⋮
// loop until results is closed.
for out := range results {
⋮
}
}
https://go.dev/play/p/FOQwybMl7tM
当然可以,但是您需要某种方法来确定何时到达结果末尾。这就是您的示例失败的原因 - 当前该函数假设将有 numjobs
(每个作业一个结果)结果并等待那么多结果。
另一种方法是使用通道关闭来指示这一点,即 (playground)
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type DemoResult struct {
Name string
Rate int
}
func random(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max-min) + min
}
func worker(id int, jobs <-chan int, results chan<- DemoResult) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
myrand := random(1, 4)
if myrand == 2 {
results <- DemoResult{Name: "succ", Rate: j}
} // else {
// results <- DemoResult{Name: "failed", Rate: 999}
//}
}
}
func main() {
const numWorkers = 3
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan DemoResult)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 1; w <= numWorkers; w++ {
go func() {
worker(w, jobs, results)
wg.Done()
}()
}
go func() {
wg.Wait() // Wait for go routines to complete then close results channel
close(results)
}()
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
for out := range results {
if out.Name == "succ" {
fmt.Printf("%v\n", out)
}
}
}
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何让Go通道工作者有不同的结果长度?》文章吧,也可关注编程网公众号了解相关技术文章。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341