From 9a5f3c9b5f2d2b1b096f1f7e84b7ca0a8a77a10c Mon Sep 17 00:00:00 2001 From: oscarzhou Date: Sun, 13 Feb 2022 18:22:23 +1300 Subject: [PATCH] doc: add the understanding about when to use channel and when to use wait group --- interview-questions.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/interview-questions.md b/interview-questions.md index fbe096d..4ad6cb6 100644 --- a/interview-questions.md +++ b/interview-questions.md @@ -16,4 +16,13 @@ A channel is a pipeline for sending and receiving data. It is like a socket that ## 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. \ No newline at end of file +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 \ No newline at end of file