SoFunction
Updated on 2025-03-01

Detailed explanation of the synchronization tool in Golang

The function is to wait for a set of goroutines to complete. When using multiple goroutines to process tasks, if you want to wait for all goroutines to complete before performing the next operation, you can use it to achieve it.

There are three methods:

  • Add(delta int): Increase or decrease the number of waiting goroutines, delta can be a negative number;
  • Done(): marks that the goroutine has been executed, equivalent to Add(-1);
  • Wait(): Wait for all goroutine execution to complete.

How to use and examples

If there are n tasks that need to be processed, you can first create a WaitGroup to wait for all tasks to complete:

var wg 

Before processing each task, call the Add method:

(1)

After each task is processed, the Done method is called once:

()

Finally, before waiting for all tasks to complete, the Wait method needs to be called:

()

The specific example code is as follows:

package main
 
import (
	"log"
	"sync"
	"time"
)
 
func main() {
	// Create a waiting group	var wg 
 
	for i := 1; i <= 5; i++ {
		// Before each task starts, add 1		(1)
 
		go func(index int) {
			// Handle business logic			//...
			(1 * )
			("The %d goroutine has been executed", index)
			()
		}(i)
	}
	// Wait for all tasks to be completed	()
	("All goroutines are executed")
}

Things to note during use

The order of Done and Add methods is very important. Done methods must be executed at the end of goroutine, otherwise it may cause the counter to fail to reach 0 correctly;
If you use Add or Done methods to change the count maintained by wg to a negative number, it will cause panic;
The Wait method will block until all goroutines are executed (the count of wg maintenance reaches 0), so you need to be careful when using it;
It is out of the box and is concurrently safe.

This is the end of this article about the detailed explanation of the synchronization tool in Golang. For more related content of the Golang synchronization tool, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!