Sobes.tech
Senior

What synchronization tools do you know in Go?

sobes.tech AI

Answer from AI

In Go, the following basic tools are used for synchronization and coordination of goroutines:

  • Mutex (sync.Mutex) — provides mutual exclusion by blocking access to shared resources.

  • RWMutex (sync.RWMutex) — an extension of Mutex that allows multiple goroutines to read simultaneously but blocks writing.

  • WaitGroup (sync.WaitGroup) — allows waiting for a group of goroutines to finish.

  • Cond (sync.Cond) — a condition variable for notifying goroutines about the occurrence of a certain state.

  • Channel (chan) — the main tool for communication and synchronization between goroutines, allowing data transfer and blocking execution until a value is received.

Example of using Mutex:

var mu sync.Mutex
var counter int

func increment() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

Example of using WaitGroup:

var wg sync.WaitGroup
wg.Add(2)
go func() {
    defer wg.Done()
    // work
}()
go func() {
    defer wg.Done()
    // work
}()
wg.Wait()

Thus, Go provides powerful and easy-to-use primitives for parallel process synchronization.

What synchronization tools do you know in Go? — Golang - sobes.tech