Signal exit condition without closing the jobs channel

blov · · 427 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><a href="https://play.golang.org/p/VMzNWjH3j3">https://play.golang.org/p/VMzNWjH3j3</a></p> <p>The workers can post additional jobs to the jobs queue, so I can&#39;t <code>close(jobs)</code> in the main goroutine and wait for the workers to exit (send on a closed channel will panic). And I can&#39;t devise another way to tell the workers that there will be no more work. Is there a way?</p> <hr/>**评论:**<br/><br/>Cidan: <pre><p>Yes, this is what context + select statements are for!</p> <p><a href="https://play.golang.org/p/hS6ajt2Lcu">https://play.golang.org/p/hS6ajt2Lcu</a></p> <p>Here you can see we did a few things:</p> <ol> <li>We created a context with cancel function in main</li> <li>We pass the context to the worker</li> <li>The worker now does a for{} and select{}</li> <li>The select statement will get a job from the queue if there is one, otherwise it waits for ctx.Done() to return -- note that ctx.Done() blocks forever, and the select statement will just keep reading from whatever channel unblocks first</li> <li>We sleep for one second in main</li> <li>We call the cancel() function, which causes ctx.Done() to close, and in turn exits us from the worker loop.</li> </ol> <p>Hope this helps, :)</p></pre>robe_and_wizard_hat: <pre><p>Why do you break out of the loop with a <code>break work</code> instead of just returning from the method?</p></pre>brokedown: <pre><p>In this case it doesn&#39;t matter but as a guide to follow that allows you to do any janitorial steps you may have after before returning.</p></pre>Nooby1990: <pre><p>You could maybe add a context.Context and close the channel when the Context is cancelled. Just have some routine (maybe main) wait for Context.Done() and close the channel afterwards. When there will be no more work just call the cancel function. The tricky part will be to detect when there is no more work and this will be dependent on the business logic you are building there.</p></pre>

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

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