Sobes.tech
Junior — Middle

Millistel tingimustel toimub blokeerimine standardandmeedastuskanaliga töötades?

sobes.tech AI

Vastus AI-lt

In Go, the standard data transmission channel blocks 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 the 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
}()

value := <-ch // reading unblocks the send
fmt.Println(value)