小编Qin*_* Qi的帖子

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

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

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

如果没有 goroutine,我们会这样做:

res, _ := redis.Get(context.Background(), "test_key").Result()
Run Code Online (Sandbox Code Playgroud)

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

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

res := <-ch
Run Code Online (Sandbox Code Playgroud)

我觉得这个方法比上面的好。我理解正确吗?

go goroutine

2
推荐指数
1
解决办法
3828
查看次数

标签 统计

go ×1

goroutine ×1