Sobes.tech
Junior — Middle

Mis vahe on kanali, millel on bufer ja millel pole buferit goroutine'ide vahelistes suhtluses?

sobes.tech AI

Vastus AI-lt

An unbuffered channel blocks the sender until the receiver reads the value, and vice versa — the receiver blocks until a value appears. This ensures synchronization between goroutines.

A buffered channel has an internal fixed-size buffer. The sender can send multiple values in a row without blocking until the buffer is full. The receiver can read values from the buffer without waiting for the sender, if the buffer is not empty.

Example:

ch := make(chan int)        // without buffer
chBuf := make(chan int, 2)  // with buffer of 2 elements

// ch <- 1  // will block if there is no receiver
chBuf <- 1 // will not block until the buffer is full

Thus, buffered channels allow more flexible synchronization management and can improve performance by reducing the number of blocks.