Junior — Middle
Is it possible to write data to a channel simultaneously without using a buffer?
sobes.tech AI
Answer from AI
Go channels can be buffered or unbuffered. In an unbuffered channel, send (write) operations block until another goroutine reads (receives) from the channel.
Simultaneous writing to an unbuffered channel is impossible because the send operation blocks until the receiver is ready, and only one sender can transmit data at a time.
To perform concurrent writes without blocking, buffered channels are used, where the sender can place data into the buffer without waiting for an immediate receiver.
Example of an unbuffered channel:
ch := make(chan int) // unbuffered channel
// Send blocks until another goroutine reads
ch <- 1
For concurrent writing without blocking, use a buffered channel:
ch := make(chan int, 2) // buffer of size 2
ch <- 1 // does not block
ch <- 2 // does not block
In summary, without a buffer, concurrent writing is impossible.