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) { 
        ....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?