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(), "test_key").Result()
with goroutine, we can do like this:
ch := make(chan string)
go func() {
res, _ := redis.Get(context.Background(), "test_key").Result()
ch <- res
}()
res := <-ch
I thought this way is better than above. Am I understand it correctly?
2
Answers
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. Usecontext.TODO()
instead. You can putcontext.Background()
at the top level.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.