Junior — Middle
How to perform data reading and writing through unbuffered channels in your system?
sobes.tech AI
Answer from AI
In Go, reading from and writing to unbuffered channels are blocking operations, meaning that a write operation blocks the goroutine until another goroutine reads the value, and vice versa.
Example:
ch := make(chan int) // unbuffered channel
// Writing to the channel (blocks until someone reads)
go func() {
ch <- 42
}()
// Reading from the channel (blocks until a value appears in the channel)
value := <-ch
fmt.Println(value) // Will print 42
Therefore, to perform read and write operations through unbuffered channels, you need to run these operations in different goroutines to avoid deadlock. This allows synchronizing data exchange between goroutines without using additional synchronization primitives.