Concurrency Basics
Worker Sequence
A single worker goroutine processes queued jobs in send order.
Worker Sequence
worker_sequence.go
package main
import "fmt"
func main() {
var extraJob =
jobs := make(chan int, 3)
results := make(chan int, 3)
go func() {
for job := range jobs {
results <- job * 10
}
}()
inputs := []int{1, 2, extraJob}
for _, job := range inputs {
jobs <- job
}
close(jobs)
first := <-results
second := <-results
third := <-results
fmt.Println("jobs=", len(inputs))
fmt.Println("first=", first)
fmt.Println("second=", second)
fmt.Println("third=", third)
}
package main
import "fmt"
func main() {
var extraJob =
jobs := make(chan int, 3)
results := make(chan int, 3)
go func() {
for job := range jobs {
results <- job * 10
}
}()
inputs := []int{1, 2, extraJob}
for _, job := range inputs {
jobs <- job
}
close(jobs)
first := <-results
second := <-results
third := <-results
fmt.Println("jobs=", len(inputs))
fmt.Println("first=", first)
fmt.Println("second=", second)
fmt.Println("third=", third)
}
package main
import "fmt"
func main() {
var extraJob =
jobs := make(chan int, 3)
results := make(chan int, 3)
go func() {
for job := range jobs {
results <- job * 10
}
}()
inputs := []int{1, 2, extraJob}
for _, job := range inputs {
jobs <- job
}
close(jobs)
first := <-results
second := <-results
third := <-results
fmt.Println("jobs=", len(inputs))
fmt.Println("first=", first)
fmt.Println("second=", second)
fmt.Println("third=", third)
}
worker
A worker reads jobs from a channel and writes results to another channel.