doc: add the understanding about when to use channel and when to use wait group

This commit is contained in:
oscarzhou 2022-02-13 18:22:23 +13:00
parent c7083f9028
commit 9a5f3c9b5f

View File

@ -16,4 +16,13 @@ A channel is a pipeline for sending and receiving data. It is like a socket that
## 4. Race condition ## 4. Race condition
In a rece condition, two things are "racing" to use the same piece of data. Problems arise when both are working with the same data at around the same time. One goroutine may be only partway through modifying a value when another goroutine tries to use it. And that situation can have unintended consequences. In a rece condition, two things are "racing" to use the same piece of data. Problems arise when both are working with the same data at around the same time. One goroutine may be only partway through modifying a value when another goroutine tries to use it. And that situation can have unintended consequences.
# When to use Channel, when to use Wait Group?
I agree with [this answer](https://stackoverflow.com/a/50166588/3409400). More specifically, I summarize my understanding below
## Channel
1. If each job's result needs to be collected, using channel is better. For example, we need to know each goroutine's error result. The error can be included in the channel struct while the signal is sent back.
2. If we want to control the number of goroutine, channel might be better since we can use channel buffer.
## Wait group
1. Wait group is easier to use and without controlling the goroutine's number