Sobes.tech
Junior

Milline on vahe buferiseeritud ja mittebuferiseeritud kanalite vahel Go-s?

sobes.tech AI

Vastus AI-lt

Channels without buffers require that data sending and receiving occur synchronously. The sender is blocked until the receiver is ready to accept the data, and vice versa. Their buffer size is zero.

Buffered channels have a finite buffer size. The sender is only blocked if the buffer is full, and the receiver if the buffer is empty.

// Unbuffered channel
unbufferedChan := make(chan int)

// Buffered channel with size 5
bufferedChan := make(chan int, 5)
Characteristic Unbuffered channel Buffered channel
Buffer size 0 > 0
Synchronization Synchronous interaction Asynchronous if buffer is not full/empty
Sender blocking Until the receiver receives Until the buffer is full
Receiver blocking Until the sender sends Until the buffer is emptied

Unbuffered channels are used for goroutine synchronization and to ensure messages are not lost. Buffered channels are used to reduce blocking, allowing the sender to continue working while the receiver is not yet ready, or vice versa.