我们应该在什么时候使用goroutine?

huangapple go评论74阅读模式
英文:

When should we use goroutine?

问题

我们应该在什么时候使用goroutine呢?我认为我们应该在需要避免阻塞程序的磁盘或网络I/O时使用它。

例如,当我们想要从Redis获取一些数据时。

没有使用goroutine时,我们可以这样做:

res, _ := redis.Get(context.Background(), "test_key").Result()

使用goroutine,我们可以这样做:

ch := make(chan string)
go func() {
    res, _ := redis.Get(context.Background(), "test_key").Result()
    ch <- res
}()

res := <-ch

我认为这种方式比上面的方式更好。我理解得正确吗?

英文:

When should we use goroutine? I thought we should use it when disk or network I/O to avoid blocking program.

For example, when we want to get some data from Redis.

Without goroutine, we do things in this way:

res, _ := redis.Get(context.Background(), &quot;test_key&quot;).Result()

with goroutine, we can do like this:

ch := make(chan string)
go func() {
res, _ := redis.Get(context.Background(), &quot;test_key&quot;).Result()
ch &lt;- res
}()

res := &lt;-ch

I thought this way is better than above. Am I understand it correctly?

答案1

得分: 9

我认为这种方式比上面的方式更好。我理解得对吗?

这是不正确的,使用goroutine没有任何优势。发生的情况是当前的goroutine会启动一个新的goroutine,然后阻塞,等待工作完成。这与没有额外的goroutine发生的情况是一样的。goroutine没有真正的区别。

当你想要同时做多个事情时,goroutine非常有用。例如,如果你有十件事情想要同时进行,你可以在每个goroutine上分别执行它们,并等待它们全部完成。

注意:你不应该在你的函数中放置context.Background()。应该使用context.TODO()代替。你可以将context.Background()放在顶层。

英文:

> I thought this way is better than above. Am i understand correct?

This is incorrect, there is no advantage to to using a goroutine that way. What happens is the current goroutine will start one new goroutine and then block, waiting for the work to finish. This is the same thing that happens without the extra goroutine. The goroutine makes no real difference.

Goroutines are useful when you want to do multiple things simultaneously. For example, if you have ten things you want to do at the same time, you can do each one on a separate goroutine, and wait for all of them to finish.

Note: You should not be putting context.Background() in your functions. Use context.TODO() instead. You can put context.Background() at the top level.

答案2

得分: 4

我们的朋友Dietrich Epp解释得非常清楚,我想要补充一些重要的内容。

Goroutine使得Go语言非常强大,例如,如果我们将线程与Goroutine进行比较:Goroutine比线程更加轻量级,线程由于其较大的堆栈大小(≥ 1MB)而消耗大量内存。因此创建1000个线程意味着你已经需要1GB的内存。
但是Goroutine只需要初始的2KB堆栈大小。

英文:

Our friend Dietrich Epp explains very clean and I wanna add something important.

Goroutine makes Go a very strong language, for example, if we compare threads with Goroutins: Goroutines are cheaper than threads, Threads consume a lot of memory due to their large stack size (≥ 1MB). So creating 1000s of threads means you already need 1GB of memory.
But Goroutine created with initial only 2KB of stack size.

huangapple
  • 本文由 发表于 2021年11月18日 23:15:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70022326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定