Go course

ChannelsBuffered Channels

Go

Display

Theme

Channels · Test exercise

Buffered Channels

You can give a channel a buffer (a capacity) with the second argument to make:

antrean := make(chan string, 3) // muat 3 nilai sebelum pengirim harus menunggu

Here's how it differs from an unbuffered channel:

Unbuffered make(chan T)Buffered make(chan T, n)
Sendblocks until there's a receiversucceeds immediately as long as the buffer isn't full
Receiveblocks until there's a sendersucceeds immediately as long as the buffer isn't empty

That means with a buffered channel you can send and receive in the same goroutine, as long as you stay within its capacity:

antrean := make(chan string, 3)
antrean <- "pesanan #1"
antrean <- "pesanan #2"

fmt.Println(len(antrean), cap(antrean)) // 2 3
fmt.Println(<-antrean)                  // pesanan #1 (FIFO: yang pertama masuk, pertama keluar)
  • cap(ch) = the buffer's capacity.
  • len(ch) = how many values are currently waiting in the buffer.

If you send a 4th value to antrean above with nobody receiving, that goroutine blocks. If it's the main goroutine and no other goroutine can receive, the program stops with a deadlock (covered in the last lesson of this chapter).

When should you use a buffer?

  • To smooth out speed differences between sender and receiver (say, the cashier takes orders faster than the barista can make them).
  • When you already know how many values will be sent, so the sender doesn't have to wait.
  • To limit how much work runs at the same time (the semaphore pattern).

A buffer is not a cure for deadlock: if there's really no receiver, a buffer only postpones the problem.

Task

A coffee shop uses a buffered channel as its order queue.

  1. buatAntrean(pesanan []string) chan string creates a channel with a capacity of exactly len(pesanan), sends every order into it in order (without goroutines), and then returns it.
  2. layani(antrean chan string, n int) []string takes the first n orders from the queue and returns them as a slice, in the order they came out. You can assume n never exceeds len(antrean).
main.go
package main

import "fmt"

func buatAntrean(pesanan []string) chan string {
	// TODO: buat channel berkapasitas len(pesanan) lalu kirim semua pesanan
	return make(chan string)
}

func layani(antrean chan string, n int) []string {
	// TODO: terima n pesanan dari antrean
	return nil
}

func main() {
	antrean := buatAntrean([]string{"latte", "kopi tubruk", "matcha"})
	fmt.Println("Menunggu:", len(antrean), "dari kapasitas", cap(antrean))
	if len(antrean) >= 2 {
		fmt.Println("Dilayani:", layani(antrean, 2))
	}
	fmt.Println("Sisa:", len(antrean))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)