Junior — Middle
Under what conditions is locking performed when working with a standard data transfer channel?
sobes.tech AI
Answer from AI
In Go, the standard data channel is blocked in the following cases:
- When sending a value to the channel (
chan <- value), if the channel is unbuffered or the buffer is full, the sending goroutine blocks until another thread reads the value. - When reading from a channel (
value := <- chan), if the channel is empty, the reading goroutine blocks until data appears.
Thus, blocking occurs when attempting to send data to a full channel or read from an empty channel, ensuring synchronization between goroutines.
Example:
ch := make(chan int) // unbuffered channel
// Sending blocks until someone reads
go func() {
ch <- 42
}()
val := <-ch // reading unblocks the send
fmt.Println(val)