Multiplexing with golang concurrency patterns

xuanbao · · 886 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So, I was having trouble with this when I was writing my golang app recently. I figured that I would share it with the community. My challenge was that I was producing lots of channels and needed to poll for results in a generic way (i.e. with interfaces). Here&#39;s the full example:</p> <pre><code>package main import ( &#34;fmt&#34; &#34;sync&#34; ) func gen(nums ...int) chan interface{} { out := make(chan interface{}, 2) go func() { for _, n := range nums { out &lt;- n } close(out) }() return out } func sq(in chan interface{}) chan interface{} { out := make(chan interface{}, 2) go func() { for n := range in { out &lt;- n.(int) * n.(int) } close(out) }() return out } // Merging generic interface channels into a single channel func merge(cs ...chan interface{}) chan interface{} { var wg sync.WaitGroup out := make(chan interface{}, 2) output := func(c chan interface{}) { for n := range c { out &lt;- n } wg.Done() } wg.Add(len(cs)) for _, c := range cs { go output(c) } go func() { wg.Wait() close(out) }() return out } func main() { in := gen(2, 3) var chs []chan interface{} chs = append(chs, sq(in)) chs = append(chs, sq(in)) for n := range merge(chs...) { fmt.Println(n.(int)) } } </code></pre> <p>And, the important parts are: </p> <ol> <li> Update <code>merge</code> method to use <code>interface{}</code>s instead of integers from the <a href="https://blog.golang.org/pipelines">community example</a>.</li> <li> Use the <code>channel_array ...</code> notation for when calling merge with a list of items. It makes it <em>super</em> nice to use <code>merge</code> for both a small number of channels and for when you have a large list of channels.</li> </ol> <hr/>**评论:**<br/><br/>Fwippy: <pre><p>Alternately; you could provide the output channel to the <code>sq</code> function, so they all write to the same combined channel (without the merging goroutines acting as middlemen).</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

886 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传