Sobes.tech
Senior

What do you know about the sync package besides Atomic and Mutex?

sobes.tech AI

Answer from AI

In the sync package in Go, besides Mutex and atomic operations, there are several useful synchronization tools:

  • WaitGroup — allows waiting for a group of goroutines to finish. It is used for coordinating parallel tasks.

  • Once — guarantees that a specific function is executed exactly once, even if called from multiple goroutines.

  • Cond — a condition variable that allows a goroutine to wait for a certain condition to occur and notify other goroutines of changes.

  • RWMutex — an extension of Mutex that allows multiple readers to lock the resource simultaneously, but only one writer.

Example of using WaitGroup:

var wg sync.WaitGroup
wg.Add(2)
go func() {
    defer wg.Done()
    // work 1
}()
go func() {
    defer wg.Done()
    // work 2
}()
wg.Wait() // wait for both goroutines to finish
What do you know about the sync package besides… - sobes.tech