gpt4 book ai didi

golang,goroutines,如何在另一个 channel 中设置 channel ,然后在关闭母 channel 后阅读

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

我是 Golang 的新手,但正在努力理解这门伟大的语言!请帮帮我..

我有 2 个 channel 。 “进”和“出” channel

    in, out := make(chan Work), make(chan Work)

我设置了在 chanel 中监听的 goroutines worker,捕获工作并完成它。我有一些工作,我会寄给香奈儿。

当 Work 由 worker 完成时,它会写入 Out channel 。

func worker(in <-chan Work, out chan<- Work, wg *sync.WaitGroup) {
for w := range in {

// do some work with the Work

time.Sleep(time.Duration(w.Z))
out <- w
}
wg.Done()
}

当所有工作完成后,我会在程序写入时关闭两个 channel 。

现在我想在 OUT channel 中写完成工作的结果,但是在某些部分中将所有内容分开,例如,如果工作类型是这样的:

type Work struct {
Date string
WorkType string
Filters []Filter
}

如果 WorkType 是“firstType”我想将完成的工作发送到一个 channel ,如果 WorkType 是“secondType”到第二个 channel ......但是可能有超过 20 种工作..如何解决这种情况以更好的方式?

我可以在chanel OUT中设置chane,然后从这个子chanel中抓取数据吗?

p.s.: 请原谅我的菜鸟问题..

最佳答案

您可以让输出 channel 是通用的,并使用类型切换处理不同的工作项。

假设您的输出 channel 只是chan interface{}

就绪工作项的消费者看起来像:

for item := range output {
// in each case statement x will have the appropriate type
switch x := item.(type) {
case workTypeOne:
handleTypeOne(x)
case workTypeTwo:
handleTypeTwo(x)
// and so on...

// and in case someone sent a non-work-item down the chan
default:
panic("Invalid type for work item!")
}
}

并且处理程序处理特定类型,即

func handleTypeOne(w workTypeOne) { 
....
}

关于golang,goroutines,如何在另一个 channel 中设置 channel ,然后在关闭母 channel 后阅读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254979/

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