Golang concurrent programming: using Go WaitGroup to implement task scheduler
WaitGroup maintains a counter internally to record the number of unfinished tasks. When the Add method is called, the counter is incremented by the specified value; when the Done method is called, the counter is decremented by 1; when the Wait method is called, if the counter is greater than 0, the current goroutine will be blocked until the counter returns to zero.
package main import ( "fmt" "sync" "time" ) func worker(id int, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("Worker %d starting ", id) time.Sleep(time.Second) fmt.Printf("Worker %d done ", id) } func main() { var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go worker(i, &wg) } wg.Wait() fmt.Println("All workers done") }
In this example, we use a for loop to start 5 worker goroutines, and add the number of tasks to the WaitGroup by calling wg.Add(1). In the worker function, use the defer keyword to ensure that wg.Done() is called before the function returns to decrement the counter value. Finally, use wg.Wait() to wait for all tasks to complete.
Worker 1 starting Worker 2 starting Worker 3 starting Worker 4 starting Worker 5 starting Worker 3 done Worker 1 done Worker 2 done Worker 5 done Worker 4 done All workers done
You can see that all worker goroutines are executed concurrently, However, the order of output is not necessarily in the startup order, because goroutine scheduling is performed by the Go runtime.
Through the introduction and sample code of this article, I believe you have a deeper understanding of how to use Golang's WaitGroup to implement a task scheduler. I hope this article will help you learn and use concurrent programming in Golang!
The above is the detailed content of Golang concurrent programming: using Go WaitGroup to implement task scheduler. For more information, please follow other related articles on the PHP Chinese website!