doulongsha5478 2016-02-07 14:54
浏览 32
已采纳

golang,goroutines,如何在另一个香奈儿中设置频道,以及在关闭母香奈儿后如何读取频道

I'm rather new in Golang, but working hard on understanding this great language! Please, help me in this..

I have 2 chanels. "In" and "Out" chanels

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

I set up goroutines workers that are listening for in chanel, grab work and do it. I have some work, that i would send into In chanel.

When Work is done by worker, it writes to the Out 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()
}

When all work is done I close both chanels at the write time of the program.

Now I want to write the results of done work in OUT chanel, but to separate all in some parts, for example, if work type would be like this :

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

if WorkType is "firstType" I would like to send the done work to one chanel, and if WorkType is "secondType" to second chan... But there might be over 20 types of work .. How to resolve this case in a better way?

Can I set up chanels in chanel OUT, and grab data from this sub chanels?

p.s.: Forgive me my noob questions, please..

  • 写回答

1条回答 默认 最新

  • doumi4974 2016-02-07 15:46
    关注

    You can have the output channel be generic, and handle different work items using a type switch.

    Say your output channel is just chan interface{}.

    The consumer of ready work items will look something like:

    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!")
       }
    }
    

    and the handlers handle a specific type, i.e.

    func handleTypeOne(w workTypeOne) { 
        ....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法