What are the ways to manage Concurrency in the Go language
This article mainly explains "what are the ways to manage Concurrency in Go language". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian to study and learn "what are the ways to manage Concurrency in Go language" together!
WaitGroup
Let's first understand what situation you need to use WaitGroup. Suppose you have two machines that need to upload the latest code at the same time. After the two machines upload separately, you can execute the final restart step. It's like splitting a job into several parts at the same time, which can reduce time, but in the end, you need to wait until all of them are done before you can execute the next step. At this time, you need to use WaitGroup to do it.
package mainimport ( "fmt" "sync")func main() { var wg sync.WaitGroup i := 0 wg.Add(3) //task count wait to do go func() { defer wg.Done() // finish task1 fmt.Println("goroutine 1 done") i++ }() go func() { defer wg.Done() // finish task2 fmt.Println("goroutine 2 done") i++ }() go func() { defer wg.Done() // finish task3 fmt.Println("goroutine 3 done") i++ }() wg.Wait() // wait for tasks to be done fmt.Println("all goroutine done") fmt.Println(i)}Channel
Another practical case is when we need to actively notify a Goroutine to stop. In other words, when the App starts, it will run some monitoring programs in the background, and when the whole App needs to stop before, you need to send a Notification to the monitoring program in the background to stop it first, then you need to use Channel to notify. Consider the following example:
package mainimport ( "fmt" "time")func main() { exit := make(chan bool) go func() { for { select { case