What did you use for synchronization in multithreading?
sobes.tech AI
Answer from AI
In Go, the following mechanisms are commonly used for synchronization in multithreading (goroutines):
-
Mutex (sync.Mutex) — for mutual exclusion access to shared resources.
-
RWMutex (sync.RWMutex) — for separating read and write access, allowing multiple readers simultaneously but blocking during writes.
-
WaitGroup (sync.WaitGroup) — for waiting for a group of goroutines to finish.
-
Channel — for data transfer and synchronization between goroutines, often the preferred method in Go.
-
Atomic operations (sync/atomic) — for low-level synchronization without locks.
Example of using Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Go often recommends using channels for synchronization, following the principle "do not communicate by sharing memory; share memory by communicating."