Home  >  Article  >  Backend Development  >  Why Use a Pointer for WaitGroup.Done but Not for WaitGroup.Add and WaitGroup.Wait?

Why Use a Pointer for WaitGroup.Done but Not for WaitGroup.Add and WaitGroup.Wait?

Susan Sarandon
Susan SarandonOriginal
2024-11-20 00:28:02758browse

Why Use a Pointer for WaitGroup.Done but Not for WaitGroup.Add and WaitGroup.Wait?

Pointers and Variables in WaitGroups Reference

In the sync package, the functions Add, Done, and Wait are all called by a pointer to a WaitGroup:

  • Add increments the wait count by the given delta.
  • Done decrements the wait count.
  • Wait blocks until the wait count is zero.

In the provided code snippet, the Done function is called using a pointer variable, while the Add and Wait functions are called using a variable (not a pointer).

However, all three functions are called on the same WaitGroup value.

  • The wg variable is declared as a value of sync.WaitGroup, but the Add, Done, and Wait methods are called on the address of wg (wg) using the dereference operator ().
  • This means that all three functions are operating on the same underlying WaitGroup value.
  • The only difference is that Done is called on the address of wg to ensure that the correct WaitGroup value is being modified.

The above is the detailed content of Why Use a Pointer for WaitGroup.Done but Not for WaitGroup.Add and WaitGroup.Wait?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn