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) | |
|---|---|---|
| Send | blocks until there's a receiver | succeeds immediately as long as the buffer isn't full |
| Receive | blocks until there's a sender | succeeds 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.
buatAntrean(pesanan []string) chan stringcreates a channel with a capacity of exactlylen(pesanan), sends every order into it in order (without goroutines), and then returns it.layani(antrean chan string, n int) []stringtakes the firstnorders from the queue and returns them as a slice, in the order they came out. You can assumennever exceedslen(antrean).