Concurrency Basics
Buffered Channel
A buffered channel can hold a small value before it is received.
buffered channel
A buffered channel can act as a deterministic handoff queue when its capacity is large enough.
Buffered Channel
buffered_channel.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var second = "green"
queue := make(chan string, 2)
queue <- "red"
queue <- second
firstOut := <-queue
secondOut := <-queue
fmt.Println("first=", firstOut)
fmt.Println("second=", secondOut)
fmt.Println("capacity=", cap(queue))
}
package main
import "fmt"
func main() {
var second = "blue"
queue := make(chan string, 2)
queue <- "red"
queue <- second
firstOut := <-queue
secondOut := <-queue
fmt.Println("first=", firstOut)
fmt.Println("second=", secondOut)
fmt.Println("capacity=", cap(queue))
}
package main
import "fmt"
func main() {
var second = "yellow"
queue := make(chan string, 2)
queue <- "red"
queue <- second
firstOut := <-queue
secondOut := <-queue
fmt.Println("first=", firstOut)
fmt.Println("second=", secondOut)
fmt.Println("capacity=", cap(queue))
}
second ← "green", queue ← (chan string)(⟨addr A⟩), firstOut ← "red"
5func main() {6 var second→ "green" = "green" //@second="blue", "yellow"7 queue→ (chan string)(⟨addr A⟩) := make(chan string, 2)89 queue(chan string)(⟨addr A⟩) <- "red"10 queue(chan string)(⟨addr A⟩) <- second"green"1112 firstOut→ "red" := <-queue(chan string)(⟨addr A⟩)13 secondOut→ "green" := <-queue(chan string)(⟨addr A⟩)14 fmt.Println("first=", firstOut"red")15 fmt.Println("second=", secondOut"green")16 fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))17}outputfirst= red second= green capacity= 2
second ← "blue", queue ← (chan string)(⟨addr A⟩), firstOut ← "red"
5func main() {6 var second→ "blue" = "blue"7 queue→ (chan string)(⟨addr A⟩) := make(chan string, 2)89 queue(chan string)(⟨addr A⟩) <- "red"10 queue(chan string)(⟨addr A⟩) <- second"blue"1112 firstOut→ "red" := <-queue(chan string)(⟨addr A⟩)13 secondOut→ "blue" := <-queue(chan string)(⟨addr A⟩)14 fmt.Println("first=", firstOut"red")15 fmt.Println("second=", secondOut"blue")16 fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))17}outputfirst= red second= blue capacity= 2
second ← "yellow", queue ← (chan string)(⟨addr A⟩), firstOut ← "red"
5func main() {6 var second→ "yellow" = "yellow"7 queue→ (chan string)(⟨addr A⟩) := make(chan string, 2)89 queue(chan string)(⟨addr A⟩) <- "red"10 queue(chan string)(⟨addr A⟩) <- second"yellow"1112 firstOut→ "red" := <-queue(chan string)(⟨addr A⟩)13 secondOut→ "yellow" := <-queue(chan string)(⟨addr A⟩)14 fmt.Println("first=", firstOut"red")15 fmt.Println("second=", secondOut"yellow")16 fmt.Println("capacity=", cap(queue(chan string)(⟨addr A⟩)))17}outputfirst= red second= yellow capacity= 2