golang,goroutines,如何在另一个频道中设置频道,然后在关闭母频道后阅读
golang, gouroutines, How to set up chanel in another chanel, and than read it after closing mother chanel
我是 Golang 的新手,但正在努力理解这门伟大的语言!请帮帮我..
我有两个频道。 "In" 和 "Out" 通道
in, out := make(chan Work), make(chan Work)
我在 chanel 中设置了正在监听的 goroutines worker,抓住工作去做。我有一些工作,我会寄给香奈儿。
当 Work 由 worker 完成时,它会写入 Out 通道。
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()
}
当所有工作完成后,我在程序写入时关闭两个通道。
现在我想把完成的工作结果写在OUT通道里,但要在某些部分分开,例如,如果工作类型是这样的:
type Work struct {
Date string
WorkType string
Filters []Filter
}
如果WorkType是"firstType"我想把完成的作品发到一个频道,如果WorkType是"secondType"到第二个频道...但是可能有20多种作品。 . 如何更好的解决这个问题?
我可以在chanel OUT中设置频道,然后从这个子频道中抓取数据吗?
p.s.: 请原谅我的菜鸟问题..
您可以将输出通道设置为通用的,并使用类型切换处理不同的工作项。
假设您的输出通道只是 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 的新手,但正在努力理解这门伟大的语言!请帮帮我..
我有两个频道。 "In" 和 "Out" 通道
in, out := make(chan Work), make(chan Work)
我在 chanel 中设置了正在监听的 goroutines worker,抓住工作去做。我有一些工作,我会寄给香奈儿。
当 Work 由 worker 完成时,它会写入 Out 通道。
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()
}
当所有工作完成后,我在程序写入时关闭两个通道。
现在我想把完成的工作结果写在OUT通道里,但要在某些部分分开,例如,如果工作类型是这样的:
type Work struct {
Date string
WorkType string
Filters []Filter
}
如果WorkType是"firstType"我想把完成的作品发到一个频道,如果WorkType是"secondType"到第二个频道...但是可能有20多种作品。 . 如何更好的解决这个问题?
我可以在chanel OUT中设置频道,然后从这个子频道中抓取数据吗?
p.s.: 请原谅我的菜鸟问题..
您可以将输出通道设置为通用的,并使用类型切换处理不同的工作项。
假设您的输出通道只是 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) {
....
}