Junior — Middle
What locking or agreement mechanism is used inside a channel to ensure synchronization and data transfer?
sobes.tech AI
Answer from AI
In Go, channels provide synchronization and data transfer between goroutines using an built-in blocking mechanism. When a goroutine sends a value into a channel, it blocks until another goroutine reads that value from the channel. Similarly, if a goroutine tries to read from an empty channel, it blocks until data becomes available.
Thus, a channel acts as a synchronization object, ensuring safe data exchange without the need to explicitly use mutexes or other synchronization primitives.
Example:
ch := make(chan int)
// Sending in a goroutine
go func() {
ch <- 42 // blocks until someone reads
}()
// Reading
value := <-ch // blocks until a value appears
fmt.Println(value)
This guarantees that data is transmitted and received synchronously.