Skip to content

Unbuffered vs buffered channels in go

Published: at 03:22 PM

Unbuffered vs Buffered channels

new

Unbuffered channels

package main
import (
	"fmt"
	"time"
)

func main() {
	// unbuffered channels have 0 cap by default
	oneChef := 0
	order := make(chan int, oneChef)
	customers := []int{1, 2, 3, 4, 5}

	go func() {
		for c := range customers {
			order <- c
			fmt.Printf("Placed order for customer %d\n", c)
		}
		close(order)
	}()

	for o := range order {
		fmt.Printf("Preparing order for customer %d\n", o)
		time.Sleep(1 * time.Second)
		fmt.Printf("Ready order for customer %d\n", o)
	}
}

Buffered channels

package main
import (
	"fmt"
	"time"
)

func main() {
	// buffered channels with 2 cap
	threeChefs := 2
	order := make(chan int, threeChefs)
	customers := []int{1, 2, 3, 4, 5}

	go func() {
		for c := range customers {
			order <- c
			fmt.Printf("Placed order for customer %d\n", c)
		}
		close(order)
	}()

	for o := range order {
		fmt.Printf("Preparing order for customer %d\n", o)
		time.Sleep(1 * time.Second)
		fmt.Printf("Ready order for customer %d\n", o)
	}
}