Junior — Middle
What are the alternative methods of communication between goroutines besides using channels?
sobes.tech AI
Answer from AI
In addition to channels, goroutines in Go can interact through:
- Shared variables with synchronization: using
sync.Mutexorsync.RWMutexfor safe access to shared data. sync.WaitGrouppackage: to wait for a group of goroutines to finish.sync.Condpackage: for conditional synchronization between goroutines.- Atomic operations from the
sync/atomicpackage for safe variable modifications without locks.
For example, for data exchange through a shared structure with a mutex:
var mu sync.Mutex
var sharedData int
func worker() {
mu.Lock()
sharedData++
mu.Unlock()
}
Thus, communication can be built not only through channels but also through synchronized access to shared resources.