Sobes.tech
Senior

What synchronization tools are available for multithreading in Go?

sobes.tech AI

Answer from AI

In Go, several main tools are used for synchronization in multithreading (goroutines):

  • Mutex (sync.Mutex) — for mutual exclusion access to shared resources.
  • RWMutex (sync.RWMutex) — an extended mutex that allows multiple readers to read simultaneously but blocks writing.
  • WaitGroup (sync.WaitGroup) — for waiting for a group of goroutines to finish.
  • Channels — the primary idiomatic way of communication and synchronization between goroutines. Channels allow data transfer and block the goroutine until data is received.
  • Atomic operations (sync/atomic) — for safe modification of variables without locks.

Example of using Mutex:

var mu sync.Mutex
var counter int

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

Example of using a channel for synchronization:

done := make(chan bool)
go func() {
    // work
    done <- true
}()
<-done // wait for completion