【问题标题】:golang, gouroutines, How to set up chanel in another chanel, and than read it after closing mother chanelgolang, goroutines, How to set up channel in another channel, and then read it after close mother chanel
【发布时间】:2016-02-07 23:52:04
【问题描述】:

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

我有 2 条香奈儿。 “进”和“出”香奈儿

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

我设置了在 chanel 中监听的 goroutines 工作人员,抓起工作并执行它。我有一些工作,我会发送到 In chanel。

当工作由工作人员完成时,它会写入输出通道。

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 chanel 中写出 done work 的结果,但是在某些部分中将 all 分开,例如,如果 work type 是这样的:

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

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

我可以在 chanel OUT 中设置 chanels,并从这个子 chanels 中获取数据吗?

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

【问题讨论】:

  • 问题是为什么每个工作类型需要单独的渠道?仅仅是因为类型定义吗?在这种情况下,您可以将其设为chan interface{}。是因为你想要单独的消费者吗?
  • 我想将不同类型Work的输出发送到不同的chanel,因为我需要以不同的方式处理每个WorkType,并且可能需要不同的输出结构......现在out chan是Work类型,但我希望能够制作像 workTypeOne、WorkTypeThree 这样的 chan...
  • 这可能吗? ..或者我怎样才能使用一个 Out 频道来实现这一点?
  • 您可以让准备好的工作项目的消费者对项目执行type switch 并相应地处理它们。我可以举个例子。
  • 这个例子会很棒。

标签: go goroutine


【解决方案1】:

您可以将输出通道设为通用,并使用类型开关处理不同的工作项。

假设你的输出通道只是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) { 
    ....
}

【讨论】:

  • 这就够了,谢谢!我会按照你的方式去做。再次感谢!
  • @Altenrion 很酷。我只会添加一个默认情况以防发送错误、恐慌或其他情况。添加到我的答案中。
猜你喜欢
  • 2022-12-01
  • 2022-11-09
  • 2022-12-26
  • 2022-12-01
  • 2022-12-19
  • 2022-12-01
  • 2022-12-28
  • 2022-12-26
  • 2022-12-01
相关资源
最近更新 更多