Go concurrency question: the same task to many processes

agolangf · · 407 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m fairly new to Go and the idea behind having one common channel (e.g. a task queue) for multiple goroutines seemed quite intuitive. A dispatcher would continuously push the tasks to the queue, and the goroutines would pop the tasks from the channel as they appear.</p> <p>However, what if I wanted to communicate the same task to multiple goroutines, e.g. the same file pointer, sent to 1000 goroutines. Followed by another 9 file pointers which would later appear in the queue (channel). </p> <p>With my current knowledge I see no other way of doing it than having my dispatcher create a separate channel for each goroutine, and push the same task to the 1000 goroutines. Repeating for each appearing task.</p> <p>Is there a better way?</p> <p>Edit: Changed &#34;process&#34; to &#34;goroutine&#34; to avoid confusion</p> <hr/>**评论:**<br/><br/>demitriousk: <pre><p>Given a desired concurrency of N -- assuming N remains static through the lift of the process -- your setup sounds fine... Make a chan for submitting processes... launch one goroutine to listen on that channel which loops N times filling a []chan then waits on the process submission channel. loop over each chan in the []chan and submit a copy or a pointer of/to the original value. You could easily wrap this into a struct with a rwmutex and the ability to resize the []chan with a stop the world event in varying ranges of complexity as necessary for the safety of your programming (a long running process probably wants very precise cleanup... whereas a cli tool which is invoked for one task and then exists can <em>probably</em> not worry about cleaning up orphaned goroutines and leave it for the exiting of the process...)</p></pre>packetlust: <pre><p>You could always just spawn the goroutines on demand with the work you have for them and let them close once they finish. Go is really fast and efficient at creating new goroutines, and this would simplify some of the bookkeeping</p></pre>

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

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