Junior — Middle
Can synchronization objects be used as arguments when calling functions?
sobes.tech AI
Answer from AI
In Go, synchronization objects such as sync.Mutex or sync.WaitGroup are usually passed by pointer to avoid copying internal state and to ensure correct operation.
Passing such objects as function arguments is possible, but it is important:
- To pass a pointer to the synchronization object, not a copy.
- Not to copy synchronization objects, as this can lead to unpredictable behavior.
Example of passing *sync.Mutex to a function:
func criticalSection(mu *sync.Mutex) {
mu.Lock()
defer mu.Unlock()
// critical section
}
func main() {
var mu sync.Mutex
criticalSection(&mu)
}
Thus, synchronization objects can be used as arguments, but they should be passed by pointer.