TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Real life concurrency in Go

29 点作者 mattetti超过 12 年前

3 条评论

jgrahamc超过 12 年前
It's a bit odd to do the time.Sleep in this code because it means that select is often not able to receive on the ch channel:<p><pre><code> select { case r := &#60;-ch: fmt.Printf("%s was fetched\n", r.url) responses = append(responses, r) if len(responses) == len(urls) { return responses } default: fmt.Printf(".") time.Sleep(5e7) } </code></pre> It would be better to use time.Tick<p><pre><code> ticker := time.Tick(50 * time.Millisecond) select { case r := &#60;-ch: fmt.Printf("%s was fetched\n", r.url) responses = append(responses, r) if len(responses) == len(urls) { return responses } case &#60;-ticker: fmt.Printf(".") } </code></pre> Also, there's no need to use a buffered channel. Each goroutine that's handling a URL get can just wait for the send on the channel before terminating.<p><pre><code> ch := make(chan *HttpResponse, len(urls)) // buffered </code></pre> can just be<p><pre><code> ch := make(chan *HttpResponse) </code></pre> And another thing that could be done is to not have asyncHttpGets return a slice of *HttpResponse but have it return a channel and then range over it. Then asyncHttpGets could run in its own goroutine and just close the channel when done.
评论 #4838201 未加载
redbad超过 12 年前
This is indeed what Go is great for. But your code example is a bit wonky :) Specifically,<p><pre><code> for { select { case r := &#60;-ch: // do something with r default: fmt.Printf(".") time.Sleep(5e7) } } </code></pre> You're needlessly blocking 50ms on every iteration. (Side note: time.Sleep(50 * time.Millisecond) better captures your intent.) Better to reformulate that as<p><pre><code> for { select { case r := &#60;-ch: // do something with r case &#60;-time.After(50*time.Millisecond): fmt.Printf(".") } } </code></pre> Or, if you don't need the dots in the output,<p><pre><code> for i := 0; i &#60; cap(ch); i++ { r := &#60;-ch // do something with r }</code></pre>
评论 #4838366 未加载
redbad超过 12 年前
<p><pre><code> Go implements OOP slightly differently than other languages. Functions are defined on an interface, not a class or subclass. </code></pre> This is not quite correct. Functions are defined on concrete types. Interfaces are named collections of functions, used to describe behavior.