Home >Backend Development >Golang >Why Use a Pointer for `Done` but Not `Add` and `Wait` with Go\'s `sync.WaitGroup`?
Understanding WaitGroup Function Signatures in GO
The sync.WaitGroup package provides functions to coordinate goroutine termination. While the three functions, Add, Done, and Wait, are all declared with pointer receivers, the provided code snippet raises a question: why is Done called using a pointer variable, while Add and Wait are called using a variable (not a pointer)?
Pointer vs. Variable Usage Clarification
Contrary to what may seem intuitive, all three functions are indeed called on a pointer to a WaitGroup. However, declaring a variable as a value of WaitGroup does not preclude accessing and modifying it through these functions, regardless of the syntax.
The crux of the matter lies in passing WaitGroup to a goroutine. If you attempt to pass it as a value, you would inadvertently create a copy, leading to a discrepancy between the Done function reference and the Add and Wait references. To circumvent this issue, the address of the WaitGroup variable is passed using &wg.
深入剖析变量和方法集合
To comprehend why this is necessary, it is crucial to delve into the underlying concepts of variables and method sets. While it may appear that calling a method on a variable is straightforward, the following rules apply:
Thus, in the provided example, the WaitGroup variable's address is passed to the worker goroutine to ensure that Done references the same WaitGroup as Add and Wait.
Conclusion
This in-depth exploration of WaitGroup function signatures has shed light on the nuanced relationship between pointers, variables, and method sets in GO. By understanding these concepts, developers can write efficient and robust goroutine synchronization code.
The above is the detailed content of Why Use a Pointer for `Done` but Not `Add` and `Wait` with Go\'s `sync.WaitGroup`?. For more information, please follow other related articles on the PHP Chinese website!