Junior — Middle
Kas on võimalik teha samaaegset andmete kirjutamist kanalisse ilma pufferita?
sobes.tech AI
Vastus AI-lt
In Go, channels can be buffered or unbuffered. In an unbuffered channel, writing (sending) is blocked until another goroutine reads the value from the channel.
Simultaneous writing to an unbuffered channel is not possible because the send operation blocks until the receive operation occurs, and only one sender can transmit data at a time.
If you need to perform simultaneous writes without blocking, buffered channels are used, where the sender can place data into the buffer without waiting for immediate reception.
Example of an unbuffered channel:
ch := make(chan int) // unbuffered channel
// Sending is blocked until someone reads
ch <- 1
For simultaneous writing without blocking, a buffer is required:
ch := make(chan int, 2) // buffer of 2 elements
ch <- 1 // does not block
ch <- 2 // does not block
Summary: without a buffer, simultaneous writing is not possible.